public static class Extensions
{
public static T TryCast<T>(this object parent)
where T : class
where this : class
{
T child = (T)Activator.CreateInstance(typeof(T));
foreach (PropertyInfo prop in parent.GetType().GetProperties())
{
child.GetType().GetProperty(prop.Name)?.SetValue(child, prop.GetValue(parent));
}
return child;
}
}
TryCast can be used as:
someString.TryCast< someClassToCastTo >()
but it is not constrained to only classes, as "where this : class" returns syntax error", which means that, without the "this : class" constriction, it will appear on variables like int, char, etc.
I am searching for a way to constrain the type "this object parent" to only class variables, as in my use case it would make no sense to use it on simple types like int and char.
Note:
It is possible to capture and restrict the parent's type like so:
public static T2 TryCastWorse<T, T2>(this T parent)
where T : class
where T2 : class
{
T2 child = (T2)Activator.CreateInstance(typeof(T2));
foreach (PropertyInfo prop in parent.GetType().GetProperties())
{
child.GetType().GetProperty(prop.Name)?.SetValue(child, prop.GetValue(parent));
}
return child;
}
And then use it like so:
someString.TryCastWorse< string, someClassToCastTo >()
This is not optimal, as one has to specify the class of the calling variable, as observed in the first type in the <>, which is a string, which should be always equal to someString.
This is not intended functionality in this case as it can introduce errors in some use cases.
Aucun commentaire:
Enregistrer un commentaire