zim*_*nen 5 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; }
}
Run Code Online (Sandbox Code Playgroud)
prop.GetValue(target)抛出以下异常:
无法对 ContainsGenericParameters 为 true 的类型或方法执行后期绑定操作。
我知道我可以这样做target.GetType().GetProperty("GetMe").GetValue(target),但我想知道是否有一种方法可以在不知道类型的情况下获取值。
简单的解决方案是拥有一个仅包含 的非泛型基类GetMe,但我现在无法进行更改。
就我个人而言,我会避免反射,并在这样的场景中使用动态关键字。
var val = ((dynamic)target).GetMe;
Run Code Online (Sandbox Code Playgroud)
但如果你真的想使用反射,下面的方法就可以了。
var val = typeof(GenericType<string>).GetProperty("GetMe").GetValue(target);
Run Code Online (Sandbox Code Playgroud)