我想知道是否可以将一个对象转换为一个Type ...我刚刚开始使用Reflection,所以也许我做错了但是这就是我想做的事情:
...
Type type = ...;
Type interfaceType = someOtherType.GetInterface("IConverter`2");
return (Cast to interfaceType)Activator.CreateInstance(type);
是否可以转换为界面?
更新
编译器说无法找到T和K. myInterface Type实例知道T和K类......
public IConverter<T, K> GetConverter(Type type)
{
if (dtoModelDictionary.ContainsKey(type))
{
Type foundType = dtoModelDictionary[type];
Type myInterface = foundType.GetInterface("IConverter`2");
return (IConverter<T, K>)Activator.CreateInstance(foundType);
}
else if (dalModelDictionary.ContainsKey(type))
{
Type foundType = dalModelDictionary[type];
return (IConverter<T, K>)Activator.CreateInstance(foundType);
}
else
{
throw new System.Exception();
}
}
第二次更新:
public SomeClass GetConverter(Type type)
{
if (dtoModelDictionary.ContainsKey(type))
{
Type foundType = dtoModelDictionary[type];
Type myInterface = foundType.GetInterface("IConverter`2");
IConverter<T, K> converter = (IConverter<T, K>)Activator.CreateInstance(foundType);
return converter.someMethod();
}
}
答案 0 :(得分:3)
回答你的更新:
您无法强制转换为未定义泛型参数的类型。必须为使用它的方法定义T和K.
要么声明:
public IConverter<T, K> GetConverter<T, K>(Type type)
或者,如果您经常遇到使用此界面的问题,但您不知道任何T或K类型,请使用没有泛型的界面:
interface IConverter
{
// general members
}
interface IConverter<T, K> : IConverter
{
// typesave members
}
public IConverter GetConverter(Type type)
{
// ...
return (IConverter)Activator.CreateInstance(type);
}
答案 1 :(得分:1)
不是真的,不......至少不是这样的。问题是你的返回值必须是你输入的方法的返回值。因为所有内容都必须在编译时输入,所以我可以看到这种特殊类型的版本有限或没有实际用例 - 也许你可以更多地谈论你想要实现的目标?
现在,如果你使用泛型,你做有一个运行时类型的故事,你可以返回你的Type参数类型:
public T MyMethod<T>(...)
...
return (T)Activator.CreateInstance(type);
答案 2 :(得分:1)
您只能将对象转换为实际的对象。例如,您可以将String
引用投射到IEnumerable
,但不能将其投射到char[]
。
如果你的方法返回的实际实现了接口,你可以像往常一样投射它。
示例:
return (IConverter<int,string>)Activator.CreateInstance(type);
编辑:
您需要使方法通用,以便在调用时指定数据类型:
public IConverter<T, K> GetConverter<T, K>(Type type) {
...
}
答案 3 :(得分:1)
你可以这样做:
var type = typeof(IConverter<,>).MakeGenericType(new Type[] { typeof(T), typeof(K) });