简体   繁体   English

C#反射:为通用方法提供T.

[英]C# reflection: providing T for a generic method

I'm not experienced using reflection and generic methods, here are two methods. 我没有使用反射和泛型方法的经验,这里有两种方法。 I think you can understand the thing I'm trying to do. 我想你可以理解我想要做的事情。

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);
}

I'm getting the following error at compile time: 我在编译时遇到以下错误:

The type or namespace name 'platformType' could not be found (are you missing a using directive or an assembly reference?). 找不到类型或命名空间名称'platformType'(您是否缺少using指令或程序集引用?)。

How can I call this method? 我怎么称呼这种方法?

Thanks in advance. 提前致谢。

Try using MakeGenericMethod . 尝试使用MakeGenericMethod

You need to get the MethodInfo for the method first. 您需要首先获取方法的MethodInfo Maybe there is a better way with using some dynamic stuff but this is the way i usually go. 也许有更好的方式使用一些动态的东西,但这是我通常的方式。 Finally you need to call Invoke . 最后你需要调用Invoke

GetPlatformType is a generic method, but instead of passing it a generic parameter, you're passing it a Type object that describes the type. GetPlatformType是一个通用方法,但是它不是传递一个泛型参数,而是传递一个描述该类型的Type对象。 A generic parameter T must be known during compile time, not passed in runtime. 通用参数T必须在编译期间已知,而不是在运行时传递。

You can use the Enum.Parse overload, passing it the Type object, but you'll have to wrap it in a try/catch block yourself (no TryParse overload). 你可以使用Enum.Parse重载,将它传递给Type对象,但是你必须自己将它包装在try / catch块中(没有TryParse重载)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM