简体   繁体   English

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

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

Assume there's a base class 假设有一个基类

class base
{
  int x, y;
}

And 3 derived singleton classes A, B, C with x, y initialized to some value. 并且将3个派生的x,y的单例类A,B,C初始化为某个值。

example : 例如:

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

Is there a way to Pass class as parameter to method and access that class's variable value. 有没有一种方法可以将类作为参数传递给方法并访问该类的变量值。 SO, One function that can update values for all 3 classes. 所以,一个函数可以更新所有3个类的值。

Intention : 目的:

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

I've seen in some posts a mention of activator.CreateInstance(classtype) in How to pass a Class as parameter for a method? 我在一些帖子中看到过在如何将类作为方法的参数传递中提到activator.CreateInstance(classtype) [duplicate] [重复]

But it doesn't answer how we can access variables of that class. 但这并不能回答我们如何访问该类的变量。

Your method needs to accept the Type and then you can access static properties because you don't have the instance. 您的方法需要接受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);
}

Although I have a feeling what you're really looking for is just simple inheritance or an interface as your parameter. 尽管我有一种感觉,您真正想要的只是简单继承或接口作为参数。

You could change Call to accept the base class that A,B,C derives from: 您可以更改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