C # reflection: providing T for a generic method

I have no experience using reflexive and general methods, here are two methods. I think you can understand what 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); } 

At compile time, I get the following error:

Unable to find type name or namespace 'platformType' (are you missing the using directive or assembly references?).

What can I call this method?

Thanks in advance.

+4
source share
2 answers

GetPlatformType is a generic method, but instead of passing it a generic parameter, you pass it a Type object that describes the type. The general parameter T must be known at compile time, and not at run time.

You can use the Enum.Parse overload by passing the Type object to it, but you will have to wrap it in a try / catch block yourself (without TryParse overload).

+2
source

Try using MakeGenericMethod .

To do this, you first need to get MethodInfo . There may be a better way to use some dynamic things, but I usually go that way. Finally, you need to invoke Invoke .

+2
source

Source: https://habr.com/ru/post/1393158/


All Articles