我有一个类类型的字典,如下所示:
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错误“实例是一个变量但是像一个类型一样使用”我如何将这个类类型传递给泛型呢?这可能吗?谢谢!
答案 0 :(得分:0)
您需要反射,因为在编译时不知道类型:
typeof(Api<>).MakeGenericType(instance.value)
.GetConstructor(new[] {typeof(Endpoint)})
.Invoke(new[]{request.Endpoint});
答案 1 :(得分:0)
以下内容针对我而且基于this post:
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)});
}
}