[英]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.