0

Is there any way to build a generic type like this?

Type underlyingType = propertyInfo.PropertyType;
Type genericType = typeof(Action<underlyingType>);

I know it may not be possible. so to get workarounds : I want to create a delegate Action<T> for setter of some properties.

var type = propertyInfo.PropertyType;
var defaultVal = type.IsValueType ? Activator.CreateInstance(type) : null;

var setter = (Action<object>)propertyInfo
    .GetSetMethod(true)
    .CreateDelegate(typeof(Action<object>), this);

var resetter = new Action(() => setter(defaultVal));
return resetter;

This does not work. because I have to pass exact matching type. If Property setter takes double I have to pass Action<double> then it works.

I have Generic container type and Underlying Type in hand. how can I mix them?


Note that I'm working on group of properties taken from a class. not a single property.

var props = GetType().GetProperties(Flags);

2 Answers 2

2

You can use Type.MakeGenericType:

Type underlyingType = propertyInfo.PropertyType;
Type genericType = typeof(Action<>).MakeGenericType(underlyingType);

You can then create the delegate (assuming you have a MethodInfo named targetMethodInfo):

Delegate = Delegate.CreateDelegate(genericType, targetMethodInfo);
Sign up to request clarification or add additional context in comments.

1 Comment

Very nice and clean approach. i will mark this as answer because it answers the question it self. (now i have another question in mind is DynamicInvoke better or SetValue or are there any better ways.)
0

I was able to do this, How ever I'm calling DynamicInvoke and it seems to be slow any way.

var ptype = propertyInfo.PropertyType;
var defaultVal = ptype.IsValueType ? Activator.CreateInstance(ptype) : null;
var type = Type.GetType($"System.Action`1[{ptype}]");
var setter = prop.GetSetMethod(true).CreateDelegate(type, this);
var resetter = new Action(() => setter.DynamicInvoke(defaultVal));
return resetter;

So maybe this approach is better.

var ptype = propertyInfo.PropertyType;
var defaultVal = ptype.IsValueType ? Activator.CreateInstance(ptype) : null;
var resetter = new Action(() => propertyInfo.SetValue(this, defaultVal));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.