gpt4 book ai didi

c# - C# 中具有零个或多个参数的通用构造函数

转载 作者:太空宇宙 更新时间:2023-11-03 21:58:08 25 4
gpt4 key购买 nike

我想知道什么是最好的方式(在 C# 中)合并我下面的两个类(这样我可以选择是否指定类型,在不需要的情况下)?另外,如果需要,推荐的编码 MyClass 以接受更多参数的方法是什么?谢谢!

public class MyClass{

public MyClass() {}
}

public class MyClass<T> {

T myvariable;

public MyClass<T>(T arg){
myvariable = arg;
}

// how can I handle MyClass(arg1, arg2, ....?
// would I need to create classes MyClass<T,U,...> for each number of argument?
}

这样我就可以 delcare MyClass...

MyClass my1 = new MyClass()
MyClass<string> my2 = new MyClass("test");

最佳答案

so that I can choose either to specify a type or not, in the case when one isn't necessary

只需合并它们并创建两个构造函数:

class MyClass<T> {

T myvariable;

public MyClass(){

}

public MyClass(T arg){
myvariable = arg;
}
}

如果不需要通用类型,请使用 Void ( void ):

public static void main(String[] args) {
final MyClass<Void> my1 = new MyClass<Void>();
final MyClass<String> my2 = new MyClass<String>("Test");
}

coding MyClass to take in more arguments if necessary

如果您需要可变数量的相同类型的参数 T ,使用可变参数:

class MyClass<T> {

T[] myvariable;

public MyClass(){

}

public MyClass(T... arg){
myvariable = arg;
}

}

无法声明可变数量的异构类型,如 <T, U, V...> .

关于c# - C# 中具有零个或多个参数的通用构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11357262/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com