I am trying to make a reference class creator. I it mostly working but dictionary I have run into some issues.
The problem is I have methods like:
static Dictionary<TKey, TVal> GetDictionary<TKey, TVal>(Type type1, Type type2)
{
var v1 = GetGeneric<TKey>(type1);
var v2 = GetGeneric<TVal>(type2);
return new Dictionary<TKey, TVal> { { v1, v2 } };
}
static T GetGeneric<T>(Type t)
{
if (t == typeof(string))
return (T)(object)" ";
if (t == typeof(int) || t == typeof(long) || t == typeof(float) || t == typeof(decimal))
return (T)(object)0;
return (T)(object)null;
}
This can be called on a PropertyInfo object info on a parent class like so:
if (p.PropertyType.Name == "Dictionary`2")
{
var t1 = p.PropertyType.GenericTypeArguments[0];
var t2 = p.PropertyType.GenericTypeArguments[1];
var ty1 = t1.BaseType;
//Kind of defeats the point here. If I make args use TKey, TVal then it blows up on casting to TKey, TVal...
var d = GetDictionary<string, string>(t1, t2);
p.SetValue(obj, d);
}
However you can see I had to set the types as they cannot gather them except explicitly. I have messed with changing the types to use Activator as well as trying expressions and such.
Ultimate the goal is to make a tool that can just make base types with defaults for many differing classes. I don't have to use reflection I just thought it would be the easiest way to do this. I can use .NET 6 so if there are newer syntax to do this, that would be prefered. I saw a lot of older code doing this here.
The duplicate suggested from what I gather I appreciate but I am not certain that is what I want. In this example you would make method to make calls to generics. I want to be able to do:
Dictionary<string, int> Dictionary<int, string> Dictionary<string, string> Dictionary<int, DateTime>
From reflection and make defaults. I have done other pieces but I am not certain if this would do much beyond make me make more methods to do this. I currently am just returning an object currently with types as my interim solution and just adding each case as they come up. But I was curious if I could do this at runtime easier.
This:
Type d1 = typeof(Dictionary<,>);
Type[] typeArgs = { p.PropertyType.GenericTypeArguments[0], p.PropertyType.GenericTypeArguments[1] };
Type constructed = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(constructed);
p.SetValue(obj, o);
Works for what I need. I just need to populate defaults.
Aucun commentaire:
Enregistrer un commentaire