[英]C# Pass Dictionary of Class Types Into Generic
我有一个类类型的字典,如下所示:
private static Dictionary<int, Type> GetArrayOfClassInstances()
{
var availability = new LeisureLinkBaseProduct.Availability();
var baseRate = new LeisureLinkBaseProduct.BaseRate();
var stayRestrictions = new LeisureLinkBaseProduct.StayRestrictions();
var checkInInformation = new LeisureLinkBaseProduct.CheckInInformation();
var specials = new LeisureLinkBaseProduct.Specials();
var taxes = new LeisureLinkBaseProduct.Taxes();
var fees = new LeisureLinkBaseProduct.Fees();
var classDictionary = new Dictionary<int, Type>();
classDictionary.Add(1, availability.GetType());
classDictionary.Add(2, baseRate.GetType());
classDictionary.Add(3, stayRestrictions.GetType());
classDictionary.Add(4, checkInInformation.GetType());
classDictionary.Add(5, specials.GetType());
classDictionary.Add(6, taxes.GetType());
classDictionary.Add(7, fees.GetType());
return classDictionary;
}
我想将它传递给这个通用方法,如下所示:
var classes = GetArrayOfClassInstances();
foreach (var instance in classes)
{
var request = RequestBuilder.BuildAdditionalDataRequest(link.href);
var response = Api<instance.value>(request.Endpoint);
}
但是我得到了intellisense错误“实例是一个变量但是像一个类型一样使用”如何将这个类类型传递给泛型呢? 这可能吗? 谢谢!
您将需要反射,因为在编译时不知道类型:
typeof(Api<>).MakeGenericType(instance.value)
.GetConstructor(new[] {typeof(Endpoint)})
.Invoke(new[]{request.Endpoint});
以下是针对我的,基于这篇文章 :
Api类:
public class Api<T>
{
public Api(Type E){}
}
创建Api方法:
private static void CreateApis()
{
var classes = GetArrayOfClassInstances();
foreach (KeyValuePair<int, Type> instance in classes)
{
Type apiType = typeof(Api<>).MakeGenericType(instance.Value);
var api = Activator.CreateInstance(apiType, new[]{typeof(System.Net.EndPoint)});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.