[英]Setting generic type only in one class
I have two generic classes: 我有两个通用类:
public class First<T>
{
...
}
public class Second<T>
{
...
}
I use Second class as parameter for First class constructor: 我使用Second类作为First类构造函数的参数:
var instance = new First<int>(new Second<int>());
Is it possible to specify generic type (integer in my example) only for First class constructor like this: 是否可以仅为First类构造函数指定泛型类型(在我的示例中为整数),如下所示:
var instance = new First<int>(new Second());
? ?
我相信通用构造函数参数的类型推断正被添加到C#6中。现在,答案是否定的。
This is my workaround suggestion, which gives you a nice syntax. 这是我的解决方法建议,它为您提供了一个很好的语法。
public class First
{
public static First<T> Create<T>(Second<T> second)
{
return new First<T>(second);
}
}
public class First<T>
{
public First(Second<T> second)
{
}
}
public class Second<T>
{
}
Use it like this: 像这样使用它:
var instance = First.Create(new Second<int>());
This is a trick that could work: (Whether or not it is good practice, I'll leave to you) 这是一个可行的技巧:(不管它是不是好的做法,我会留给你)
public class Second { }
Inside the Second<T>
class: 在Second<T>
类中:
public static implicit operator Second<T>(Second second) {
return new Second<T>();
}
This will only work if the First<T>
constructor ONLY accepts Second<T>
and not another Second<U>
or something. 这仅在First<T>
构造函数ONLY接受Second<T>
而不是另一个Second<U>
情况下才有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.