dimanche 4 janvier 2015

Initialize Property of Generic Type

I have read multiple posts but haven't found an appropriate answer for my problem. But there has to be one. So please be patient if this post really is an duplicate.


I try to initialize a Property of a generic type implementing a generic interface.


My interface looks basically like this:



public interface IMyInterface<TType> : IMyInterface
{
TType Value {get; set;}

// ... and some more ...
}

public interface IMyInterface
{
SetValue(string value);
}


I have multiple Classes implementing IMyInterface without knowing them at the piece of code, where I need to set the value.


Is it possible to inizialize the "Value"-Property without using the Name of the property? (Is there a "nice" way to do this?) - It isn't possible to use SetValue< TType >



void SetValue(object obj, string value)
{
// object obj implements IMyInterface<???>
PropertyInfo valueInfo = typeof(obj).GetType().GetProperty("Value")
valueInfo.SetValue(obj, Activator.CreateInstance(valueInfo.PropertyType))

((IMyInterface)obj).SetValue(value);
}


Thanks in advance.






Aucun commentaire:

Enregistrer un commentaire