我有這樣的代碼有沒有辦法處理未知的泛型類型?
public interface IConsumable<T> {
void Consume(T item);
}
public interface IProducer<T> {
IConsumable<T> Consumer { get; set; }
void Produce();
}
public class MyClass : MyType,
IConsumable<ISpecifcItem>
{
public void Consume(ISpecificItem item) { ... }
}
public class MySpecificItemProducer
: IProducer<ISpecificItem> {
public IConsumable<ISpecificItem> Consumer { get; set; }
public void Produce() {
ISpecificItem myItem = new MyVerySpecificItem();
Consumer.Consume(myItem);
}
}
然後我有一個控制器,它採取任何MyType
,發現各類IConsumable<>
它實現並得到泛型類型參數的類型。有了這個類型列表,它可以發現實現IProducer<TParam>
的所有生產者。這並不難:
var consumerTypes =
myType.GetType().GetInterfaces()
.Where(x => x.IsGenericType)
.Where(x => x.GetGenericTypeDefinition() ==
typeof(IConsumable<>));
if (consumerTypes.Any()) {
var instanceTypes = consumerTypes
.Select(x => x.GetGenericArguments().First())
.Select(x => typeof(IProducer<>).MakeGenericType(x));
// for each of those types discover classes where
// it assignable from
// and instantiate the class using the Activator
}
但問題是,我該如何設置生產者的消費者屬性?生產者實例對我來說是一個對象,我不能將它轉換爲IProducer<T>
,因爲我不能像變量那樣使用T.
我可以用反射producerInstance.GetType().GetProperty("Consumer").SetValue(producerInstance, consumerInstance, null);
但我想知道是否有另一種方式嗎?
有趣的是,這並沒有在運行時:
MyClass consumerInstance;
dynamic test = producerInstance;
test.Consumer = consumerInstance;
這抱怨那consumerInstance的類型是不兼容的屬性的類型。
編輯:動態例子只是工作時,consumerInstance也是一個動態的,例如:
dynamic testC = consumerInstance;
dynamic testP = producerInstance;
testP.Consumer = testC;
您的動態代碼適合我。 – Ani 2012-03-01 12:09:59
嗯好吧,我只是試過一次,也許別的東西。 – Andreas 2012-03-01 13:22:53
我跟進了這個動態的例子,發現它在我讓受讓人也是動態的時候起作用。 – Andreas 2012-03-11 21:03:03