繁体   English   中英

C#是否可以将Class类型作为参数传递给Function并访问方法内部的类变量

[英]C# Can we pass Class type as parameter to Function and access class variables inside method

假设有一个基类

class base
{
  int x, y;
}

并且将3个派生的x,y的单例类A,B,C初始化为某个值。

例如:

class A : base { x = 1; y = 0;}
class B : base { x = 0; y = 1;}    
class C : base { x = 1; y = 1;}

有没有一种方法可以将类作为参数传递给方法并访问该类的变量值。 所以,一个函数可以更新所有3个类的值。

目的:

int call (type classtype)
{
   int xvalue = classtype.x;
   int yvalue = classtype.y;
}

我在一些帖子中看到过在如何将类作为方法的参数传递中提到activator.CreateInstance(classtype) [重复]

但这并不能回答我们如何访问该类的变量。

您的方法需要接受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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM