使用开放定义从通用 class 上的 属性 获取值

Get value from property on generic class using open definition

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

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) 抛出以下异常:

Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.

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

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

当您使用 typeof(GenericType<>) 时,您没有为您的类型提供 T 参数,因此运行时无法获取 属性 的值。 这里需要使用.GenericTypeArguments[0],像这样:

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

查看原文post以获取更多信息:

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

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

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

就我个人而言,我会完全避免反射,并在这种情况下使用 dynamic 关键字。

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

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

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