对于实现者类,接口是否有自动通用的方法?
例如,我想创建一个接口,该接口将从实现类返回委托。 (实际上我希望它返回一个包含多个函数的数组,但我在这里简化了。)
以下内容应该有效:
public interface IParentFinder<ChildClass>
{
Func<ChildClass, int> GetParentIdFunction();
}
然后要实现它,我必须写下这个:
public class AClass : IParentFinder<AClass>
{
int id;
int parentId;
static public Func<AClass, int> GetParentIdFunction()
{
return c => c.parentId;
}
}
但是我只希望在通用模板与实现类匹配的地方使用此接口。我可以使用一些方便,所以我可以写这个:
public class AClass : IParentFinder
{
...
}
我希望有一些baseType
参数可用于指定泛型的基本类型。例如:
public interface IParentFinder
{
Func <baseType, int> GetParentIdFunction();
}
为了清晰起见而编辑
答案 0 :(得分:0)
不,C#中没有这样做的功能。
答案 1 :(得分:0)
与任何其他参数(方法或通用参数)一样,通用接口类型参数需要参数。没有参数的参数根本不是参数。
也许C#vNext可以实现默认通用参数值:
public class A<T> where T : default(string) { ... }
......或者谁知道什么。但是,目前,通用参数需要参数。而且,毕竟,这不适合你在你的案例中寻找的东西 - 自动神奇的通用参数...... - 。