【发布时间】:2017-03-20 12:36:17
【问题描述】:
我需要创建两个部分接口。一个有约束,另一个没有,比如:
public partial interface IMyCuteInterface<T> where T : IEnumerable
{
void DoSomethingOnlyPossibleIfGenericIsIEnumerable();
}
public partial interface IMyCuteInterface<T>
{
void DoSomeStuff();
void DoSomeStuff2();
}
这是实现:
public class CuteInterfaceImplementation<T> : IMyCuteInterface<T>
{
private readonly T _element;
public CuteInterfaceImplementation(T element)
{
_element = element;
}
public void DoSomethingOnlyPossibleIfGenericIsIEnumerable(){}
public void DoSomeStuff(){}
public void DoSomeStuff2() { }
}
这是一种更动态地获取它的静态方法:
public class CuteInterfaceImplementationBase
{
public static IMyCuteInterface<T> From<T>(T t)
{
return new CuteInterfaceImplementation<T>(t);
}
}
我想这样称呼它:
public static void Main(string[] args)
{
var mci = CuteInterfaceImplementationBase.From(args);
}
所以,C# 想要我将我在第一个接口中添加的泛型类型约束添加到我的CuteInterfaceImplementationBase.From<T> 和我的CuteInterfaceImplementation<T>-class。
我想要实现的是:args 可以是例如来自List<T> 类型或int 类型或其他类型。我的目标是,如果args 来自IEnumerable<T> 类型,我想向CuteInterfaceImplementation-instance 添加更多功能(通过带有约束的接口)。
示例:
如果 args 来自类型 IEnumerable,则来自 CuteInterfaceImplementation 的此实例具有方法:
void DoSomethingOnlyPossibleIfGenericIsIEnumerable();void DoSomeStuff();void DoSomeStuff2();
如果 args 来自 Foo 或 int 类型(或任何未实现 IEnumerable 的类型),我可以使用方法:
void DoSomeStuff();void DoSomeStuff2();
表示DoSomethingOnlyPossibleIfGenericIsIEnumerable 不可用。
但这似乎是不可能的,因为我需要将约束添加到我实现的类中。知道怎么做吗?
【问题讨论】:
-
我认为
partial的目的是拆分定义,而不是你想要的。 -
如果你的类包含 DoSomethingOnlyPossibleIfGenericIsIEnumerable - 那么泛型应该是 IEnumerable,你应该不能将该类与任何其他类型一起使用(顺便说一下
partial在这里无关紧要,可能你不明白partial 的真正作用)。 -
对不起@Evk,但我知道 partial 的作用。你的评论只是重复了我所说的。是的,这是不可能的。我的问题是,我怎样才能让它发挥我在帖子中解释的作用。
标签: c# generics interface type-constraints