假设有一个基类
class base
{
int x, y;
}
3派生了singleton类A、B、C,其中x、y初始化为某个值。
示例:
class A : base { x = 1; y = 0;}
class B : base { x = 0; y = 1;}
class C : base { x = 1; y = 1;}
是否有方法将类作为参数传递给方法并访问该类的变量值。SO,一个可以更新所有3个类的值的函数。
意向:
int call (type classtype)
{
int xvalue = classtype.x;
int yvalue = classtype.y;
}
我在一些帖子中看到了activator。中的CreateInstance(类类型)如何将Class作为方法的参数传递?[副本]
但它并没有回答我们如何访问该类的变量。
您的方法需要接受Type
,然后才能访问静态属性,因为您没有实例。
int Call(Type classType)
{
var xvalue = (int)classType.GetProperty("x", BindingFlags.Public | BindingFlags.Static).GetValue(null, null);
var yvalue = (int)classType.GetProperty("y", BindingFlags.Public | BindingFlags.Static).GetValue(null, null);
}
尽管我有一种感觉,您真正想要的只是简单的继承或作为参数的接口。
您可以更改Call
以接受A、B、C派生自的基类:
int Call(base theClass)
{
if (theClass is A)
{
var ax = theClass.x;
var ay = theClass.y;
}
else if (theClass is B)
{
// etc
}
// etc
}