[英]C# reflection: providing T for a generic method
我沒有使用反射和泛型方法的經驗,這里有兩種方法。 我想你可以理解我想要做的事情。
public static T GetInHeaderProperty<T>() where T : new()
{
dynamic result = new T();
result.CompanyId = ConfigurationManager.AppSettings["CompanyId"];
result.UserId = ConfigurationManager.AppSettings["UserId"];
result.Password = ConfigurationManager.AppSettings["Password"];
result.MessageId = ConfigurationManager.AppSettings["MessageId"];
Type platformType = typeof(T).GetProperty("PlatformType").PropertyType;
// Here is my problem, I can not compile my code because of this line
result.PlatformType = (dynamic)GetPlatformType<platformType>();
//-------------------------------------------------------------------
return (T)result;
}
public static T GetPlatformType<T>() where T : struct
{
string platform = System.Configuration.ConfigurationManager.AppSettings["Platform"];
T value;
if (Enum.TryParse(platform, out value))
return value;
else
return default(T);
}
我在編譯時遇到以下錯誤:
找不到類型或命名空間名稱'platformType'(您是否缺少using指令或程序集引用?)。
我怎么稱呼這種方法?
提前致謝。
嘗試使用MakeGenericMethod 。
您需要首先獲取方法的MethodInfo 。 也許有更好的方式使用一些動態的東西,但這是我通常的方式。 最后你需要調用Invoke 。
GetPlatformType是一個通用方法,但是它不是傳遞一個泛型參數,而是傳遞一個描述該類型的Type對象。 通用參數T必須在編譯期間已知,而不是在運行時傳遞。
你可以使用Enum.Parse重載,將它傳遞給Type對象,但是你必須自己將它包裝在try / catch塊中(沒有TryParse重載)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.