【问题标题】:C# Can we pass Class type as parameter to Function and access class variables inside methodC#我们可以将类类型作为参数传递给函数并访问方法内的类变量吗
【发布时间】:2018-04-02 02:26:25
【问题描述】:

假设有一个基类

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;}

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

意图:

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

我在一些帖子中看到了 activator.CreateInstance(classtype) How to pass a Class as parameter for a method? [duplicate]

但它没有回答我们如何访问该类的变量。

【问题讨论】:

  • 它应该是int call (base classtype),你会传递实例化的对象。
  • type 没有这些变量。该类型的 Instances 具有这些变量,因此具有 type 不会给您任何变量。
  • 请显示“类 A,B”的代码 - 非常不清楚 @Servy 所说的“类的变量值”是什么意思。您可能指的是静态类字段/属性 实例字段/属性 - 如果代码实际上是 C# 而不是某种伪语言,那就很清楚了。
  • @AlexeiLevenkov :我知道类型不提供任何变量。这就是为什么我将其解释为回报的意图。此外,A、B 和 C 只不过是扩展相同的变量并初始化为让我们 A(1,0) B(0,1) 和 C(1,1)。现在我期待更新这些初始化值运行时。我不想为 3 个类实现 3 个函数,所以想知道我们是否可以简单地为所有 3 个类实现一个泛型。

标签: c# function class oop parameter-passing


【解决方案1】:

您可以更改 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
}

【讨论】:

  • 通常当您发现自己这样做时,这是代码异味的迹象。而不是有一堆is检查你只需做两个重载Call(A theClass)Call(B theClass)
  • 问题是 A、B 和 C 的功能是相同的,并且为每个类设置不同的功能/过程效率不高,相反我们应该能够发送一个 para 并取决于该创建/访问相应类的实例。
【解决方案2】:

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

虽然我感觉您真正要寻找的只是简单的继承或接口作为参数。

【讨论】:

  • 你怎么称呼这个方法?
  • @Steve Call(typeof(MyType))
  • 这个结果(对我来说)是由 GetProperty 返回的空值,而 NRE 紧随其后
  • 你好 Yuriy,看起来要获得一个变量的值太费劲了。在我的情况下,有 40-50 个变量。它还需要为该类 var 分配值的能力。我忘了说 A、B、C 是单例类。
  • 这只会在运行时抛出异常,因为类型上没有这样的静态字段。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-27
  • 1970-01-01
  • 1970-01-01
  • 2014-04-03
  • 1970-01-01
  • 2015-12-26
相关资源
最近更新 更多