使用开放式定义从泛型类的属性中获取值

时间:2015-03-23 18:37:55

标签: c# generics reflection

有没有办法使用反射从开放类型中获取属性的值?

class Program
{
    static void Main(string[] args)
    {
        var target = new GenericType<string>();
        target.GetMe = "GetThis";
        target.DontCare = "Whatever";

        var prop = typeof(GenericType<>).GetProperty("GetMe");
        var doesntWork = prop.GetValue(target);
    }
}

public class GenericType<T>
{
    public string GetMe { get; set; }
    public T DontCare { get; set; }
}

prop.GetValue(target)抛出以下异常:

  

无法对ContainsGenericParameters为true的类型或方法执行后期绑定操作。

我知道我可以做target.GetType().GetProperty("GetMe").GetValue(target),但我想知道是否有办法在不知道类型的情况下获取价值。

简单的解决方案是拥有一个仅包含GetMe的非泛型基类,但我现在无法进行更改。

3 个答案:

答案 0 :(得分:4)

就个人而言,我只是避免一起反思,并使用dynamic关键字来表示这样的情况。

var val = ((dynamic)target).GetMe;

但是如果你真的想使用反射,下面的方法就可以了。

var val = typeof(GenericType<string>).GetProperty("GetMe").GetValue(target);

答案 1 :(得分:1)

是的,问题是您的typeof(GenericType<>)会创建一个代表不完整类型的Type对象。您只能使用完整的类型对象获取值。

您需要先获取完整的类型对象。由于您已经有一个可以处理的对象,因此您可以使用该对象中的类型

    var prop = target.GetType().GetProperty("GetMe");
    var doesWork = prop.GetValue(target);    

答案 2 :(得分:0)

当您使用typeof(GenericType<>)时,您不会为您的类型提供T参数,因此运行时无法获取属性的值。 你需要在这里使用.GenericTypeArguments[0],如下所示:

var prop = typeof(GenericType<>).GenericTypeArguments[0].GetProperty("GetMe");

请参阅原帖以获取更多信息:

https://stackoverflow.com/a/12273584/213550

相关问题