Quick one here~ I want to convert < T > ToString so I can replace the variable with that type~
public void ChangePanel<T>(T Action){
FieldInfo Field = T.GetField(T.toString);
Field.SetValue(SomeObject, Action);
}
Also please let me know if there is a better way to do this!!
Edit: FYI the variables in SomeObject have the same name as type
You can use the typeof
Keyword to get a Type instance, and the Type.Name Property to get the type's name.
public void ChangePanel<T>(T action)
{
Type typeOfObject = someObject.GetType();
Type typeOfAction = typeof(T);
FieldInfo field = typeOfObject.GetField(typeOfAction.Name);
field.SetValue(someObject, action);
}
Yes. ToString()
is defined on the object
class which everything derives from so I would expect you can call it on any type T
. However, you need to call it on the parameter itself, not the type, so rather than doing T.ToString()
you should be doing Action.ToString()
. If you want to get the name of the type then you should use reflection rather than ToString
.
Also, the reflection options are either;
typeof(T).Name
or
Action.GetType().Name
If you want to get the name of a generic type, then you can simply call typeof(T).Name
:
public static string GetGenericTypeName<T>()
{
return typeof(T).Name;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With