![](/img/trans.png)
[英]Getting the name of a type of generic property of class definition using Roslyn
[英]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)
引發以下異常:
無法對包含ContainsGenericParameters為true的類型或方法執行后期綁定操作。
我知道我可以做target.GetType().GetProperty("GetMe").GetValue(target)
,但是我想知道是否有一種方法可以在不知道類型的情況下獲取值。
一個簡單的解決方案是擁有一個僅包含GetMe
的非泛型基類,但是我現在無法進行更改。
就我個人而言,我只是避免一起思考,而將動態關鍵字用於這種情況。
var val = ((dynamic)target).GetMe;
但是如果您真的想使用反射,則可以使用以下方法。
var val = typeof(GenericType<string>).GetProperty("GetMe").GetValue(target);
是的,問題是您的typeof(GenericType<>)
創建了一個Type
對象,該對象表示一個不完整的類型。 您只能使用完整的類型對象獲取值。
您需要首先獲取完整的類型對象。 由於您已經有一個要處理的對象,您可以只使用該對象中的類型
var prop = target.GetType().GetProperty("GetMe");
var doesWork = prop.GetValue(target);
使用typeof(GenericType<>)
,沒有為類型提供T
參數,因此運行時無法獲取屬性的值。 您需要在此處使用.GenericTypeArguments[0]
,如下所示:
var prop = typeof(GenericType<>).GenericTypeArguments[0].GetProperty("GetMe");
請參閱原始帖子以獲取更多信息:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.