繁体   English   中英

C#通用参数

[英]C# generic parameters

假设我有一些通用interface IMyInterface<TParameter1, TParameter2>

现在,如果我正在编写另一个类,则它的参数T通用的:

CustomClass<T> where T : IMyInterface

应该怎么做?

(当前代码不能编译,因为IMyInterface是依赖于TParameter, TParameter2 )。


我认为应该这样做:

CustomClass<T, TParameter1, TParameter2> where T: IMyInterface<TParameter1,
                                                               TParameter2>

但是我可能是错的, 请您告诉我一下吗?

这正是因为你拥有它,你需要指定TParameter1TParameter2在需要对通用约束的一类通用参数IMyInterface

public interface IMyInterface<TParameter1, TParameter2>
{ 
}

public class CustomClass<T, TParameter1, TParameter2> 
    where T : IMyInterface<TParameter1, TParameter2>
{

}

或者您可以修复它们:

public class CustomClass<T> 
    where T : IMyInterface<string, int>
{

}

您是否真的想将其用作约束(与“ where”关键字一起使用)? 以下是一些直接实现的示例:

interface ITwoTypes<T1, T2>

class TwoTypes<T1, T2> : ITwoTypes<T1, T2>

或者,如果您知道您的类将使用的类型,则无需在类上使用类型参数:

class StringAndIntClass : ITwoTypes<int, string>

class StringAndSomething<T> : ITwoTypes<string, T>

如果您使用接口作为约束并且不知道要显式指定的类型,那么可以,您需要按照预期的那样将类型参数添加到类声明中。

class SomethingAndSomethingElse<T, TSomething, TSomethingElse> where T : ITwoTypes<TSomething, TSomethingElse>

class StringAndSomething<T, TSomething> where T : ITwoTypes<string, TSomething>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM