C# 如何为返回实现接口的类类型的方法创建泛型接口?
我正在寻找一种在下面定义“MethodA”的方法,这样它将返回一个类定义(System.Type),其中所述类型的实例将实现“InterfaceB”C# 如何为返回实现接口的类类型的方法创建泛型接口?,c#,generics,types,interface,C#,Generics,Types,Interface,我正在寻找一种在下面定义“MethodA”的方法,这样它将返回一个类定义(System.Type),其中所述类型的实例将实现“InterfaceB” 接口IMyInterface { t类型MethodA() :其中TType:System.Type :其中[instanceOf(TType)]:TInterface } (注意:instanceOf当然不是真的…) 我怀疑不可能在编译时得到这种验证。我希望有人能证明我错了 提前感谢您的指导 编辑:我更新了这个,希望更具体地说,返回的是Syst
接口IMyInterface
{
t类型MethodA()
:其中TType:System.Type
:其中[instanceOf(TType)]:TInterface
}
(注意:instanceOf当然不是真的…)
我怀疑不可能在编译时得到这种验证。我希望有人能证明我错了
提前感谢您的指导
编辑:我更新了这个,希望更具体地说,返回的是System.Type,后面的代码可以执行它:
var classType=myInterface.MethodA();
ISomeInterface=新类类型()//--假设默认构造函数
我还没有真正关注这一部分,只是对我的主要问题的理论结构更感好奇。你的问题有两种解释;一个是琐碎的,一个是不可能的,所以我将继续讨论这两个问题
TInterface
的类型的实例
这很简单:只需使用where TType:Type
和where TType:TInterface
TInterface
继承的类型
这在.NET(和C#)类型系统中是不可能指定的
类型系统只能解析来自类型层次结构本身的信息,但不能强制执行“契约”,如受限制的运行时属性值。关于默认构造函数等有一些黑客,但据我所知,甚至不可能对现有方法进行测试(例如,与C++模板不同,不必说Qi等人)。
// We have an interface...
interface InterfaceB {}
// And this class implements the interface.
class ImplementsB : InterfaceB {}
// But this class does not.
class DoesNotImplementB {}
您可以将MethodA
定义为:
static Type MethodA<TClass, TInterface>()
where TClass : TInterface
{
return typeof(TClass);
}
如果您知道您的类型
与某些接口TInterface
兼容,则可以使用以下附加方法避免强制转换:
public object Instantiate(Type type)
{
// Call the default constructor.
// You can change this to call any constructor you want.
var constructor = type.GetConstructor(Type.EmptyTypes);
var instance = constructor.Invoke(new object[0]);
return instance;
}
public TInterface Instantiate<TInterface>(Type type)
{
return (TInterface)Instantiate(type);
}
请注意,typeof(TType)
是一个表达式,它产生一个Type
对象,因此无论在哪里看到typeof()
都可以用任何Type
变量替换它,反之亦然
这是您想要知道的吗?将返回类型更改为
TInterface
您使用“type”是指System.type
,还是指您定义的某种类型?在前一种情况下,由于明显的原因,您试图做的是不可能的,而且您几乎肯定不应该从System.Type
派生。是的,我是指System.Type。我想看看是否可以得到实现TInterface的某些东西的类定义,稍后我将对其进行“更新”。我正试图避免用这种特殊的方法来更新它。他用“Type”这个词来指的不是System.Type
。你说得太对了。哎哟对于其他读者:属于类2。)检查属性值不起作用。对于#1,我将其简化为TType:Type,TInterfaceClose,但我试图避免在此时实际实例化对象。我想返回类定义本身,稍后可以使用它来实例化对象。我的问题是,我无法找到一种方法来保证返回的(System.Type)在实例化时实际实现了TInterface。至少,在我尝试实例化它并将其转换到TInterface之前。但这是一个运行时解决方案,不是编译时解决方案。我更新了我的帖子。这更接近你想知道的吗?我没有忘记这一点,我只是没有时间应用你的想法。它们听起来不错,也许这个周末我会有机会试用它们,并在可能的时候更新这个评论栏。
Type t = MethodA<ImplementsB, InterfaceB>();
Type t = MethodA<DoesNotImplementB, InterfaceB>();
public object Instantiate(Type type)
{
// Call the default constructor.
// You can change this to call any constructor you want.
var constructor = type.GetConstructor(Type.EmptyTypes);
var instance = constructor.Invoke(new object[0]);
return instance;
}
public TInterface Instantiate<TInterface>(Type type)
{
return (TInterface)Instantiate(type);
}
public TInterface Instantiate<TInterface>(Type type)
{
if (!typeof(TInterface).IsAssignableFrom(type))
throw new Exception("Wrong type!");
return (TInterface)Instantiate(type);
}