【问题标题】:Dynamically detect which child class is packed in base-class type object动态检测基类类型对象中包装了哪个子类
【发布时间】:2014-07-08 16:02:51
【问题描述】:

我有一个方法,它获取一个基类类型的变量,但我将子类的变量传递给这个方法。

简单示例:

public class Shape {
    public string Color {get;set;}    
}

public class Square : Shape {
    public int Corners {get;set;}    
}

public class Circle : Shape {
    public int Radius {get;set;}    
}

一些方法如:

public void GetDetails(Shape item){
    // do something        
}

然后我将子类对象传递给这个方法:

var sq = new Square();
var cir = new Circle();
var corners = GetDetails(sq);
var radius = GetDetails(cir);

问题:

这种方法如何检测实际出现的类型?假设在 foreach 循环中我遍历列表,所以我无法知道每个项目的真正类型(方形或圆形)。

我的实际问题是:

我将不同的子类类型变量打包到基类类型列表中。然后我将此列表发送到一个方法,在其中我想获取每个类的所有属性。我通过“反射”实现它,但方法 .GetProperties() 只返回基类的属性,但我还需要派生类的属性。

【问题讨论】:

    标签: c# asp.net c#-4.0 reflection


    【解决方案1】:

    您应该使用GetType() 来获取对象的动态(实际)类型:

    public void GetDetais(Shape item)
    {
        var properties = item.GetType().GetProperties();
    }
    

    如果您使用typeof(),您将使用编译时类型,该类型始终为Shape

    【讨论】:

      【解决方案2】:

      使用is关键字

      if (item is Square) {...};
      if (item is Circle) {...};
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-19
        • 2019-11-10
        • 2019-10-17
        • 2011-01-14
        • 2019-05-18
        • 2014-04-04
        • 2012-07-12
        • 2017-11-30
        相关资源
        最近更新 更多