简体   繁体   中英

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?).

How can I call this method?

Thanks in advance.

Try using MakeGenericMethod .

You need to get the MethodInfo for the method first. 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 .

GetPlatformType is a generic method, but instead of passing it a generic parameter, you're passing it a Type object that describes the type. A generic parameter T must be known during compile time, not passed in runtime.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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