【发布时间】:2019-10-04 03:02:12
【问题描述】:
我试图将类与其他设置或更改类中的数据隔离开来。我选择使用一个名为 Parent 的抽象基类,然后使用两个名为 DerivedA 和 DerivedB 的派生抽象类。然后,使用 Assembly,我从 Parent 获取派生的抽象类。然后,我使用泛型派生一个具体类 ConcreteGeneric,希望能填充抽象类的值。
我遇到的问题是,当我进入我的具体类时,我无法访问(查看)父类成员/属性。也许这个设计都是错误的,但这是我想解决它的理想方式。任何帮助将不胜感激......并保存从我头上掉下来的头发。 ;)
附上代码。
我已经在代码中记录了我想要的内容。能够访问和查看父类中的公共变量。
using System;
using System.Linq;
using System.Reflection;
public abstract class Parent
{
public string Name { get; set; }
public string Comment { get; set; }
}
public abstract class DerivedA : Parent
{
public string DerivedAString { get; set; }
}
public abstract class DerivedB : Parent
{
public string DerivedBString { get; set; }
}
public class DerivedFromA : DerivedA
{
public string DerivedFromAString { get; set; }
}
public class ConcreteGeneric<T> where T : Parent
{
private string _jsonString = "";
public string HeaderString
{
get
{
return _jsonString;
}
set
{
/// I want to be able to see the Derived classes parameters
/// here. Like 'DerivedB.DerivedBString' if T is type DerivedB
_jsonString = value;
}
}
}
public class RunItClass
{
public static void Main()
{
Type[] types = Assembly.GetAssembly(typeof(Parent)).GetTypes();
foreach (Type type in Assembly.GetAssembly(typeof(Parent)).GetTypes()
.Where(myType => myType.IsAbstract && myType.IsSubclassOf(typeof(Parent))))
{
var genType = typeof(ConcreteGeneric<>).MakeGenericType(type);
Type genericType = (Type)genType;
object genericInstance = Activator.CreateInstance(genericType);
dynamic dynamicObj = Convert.ChangeType(genericInstance, genericType);
/// Note that when I drop into the 'set' method on this dynamic object, I cannot see the
/// paramters of the parent class, which is 'DerivedA' on the first item in this loop.
dynamicObj.HeaderString = "Testing";
// Testing here
if (genericType == typeof(ConcreteGeneric<DerivedA>))
{
// ?? I CANNOT see all of the variables in 'DerivedA' ??
ConcreteGeneric<DerivedA> da = (ConcreteGeneric<DerivedA>)genericInstance;
/// I CAN see all of the variables in 'DerivedA' and also 'Parent'. This is what I
/// am after, but I want to be able to use the ConcreteGeneric<![CDATA[>]]> to accomplish this.
/// Please help. :)
DerivedFromA dfa = new DerivedFromA();
Console.WriteLine();
}
}
}
}
【问题讨论】:
-
请注意您的标题具有误导性 - 您的泛型类没有父类
标签: c# proxy abstract-class derived-class