如何调用构造函数没有新的? [英] How to call constructor without new?
问题描述
我知道该字符串就像是一个类,并创建一个新的字符串时字符串本身犯规欠的价值,但只有价值的指针。但创建一个字符串时,有没有必要使用新词;
字符串=你好;
而不是
串=新的字符串(你好);
我知道,第二个选项也有可能,但我想知道究竟是为什么第一个?
让我们说我有一个类名的学生,他的构造得到了字符串
。要创建一个新的类,我必须使用保存的新词
学生例如=新的学生(萨布丽娜);
我试过超载算符=
,但它是不可能的。
我怎样才能创建像字符串的新类
做(不使用这个词新
)?
学生例如=萨布丽娜;
您可以使用转换操作符隐式:
密封类学生
{
公共字符串名称
{
搞定;
私人集;
}
学生()
{
}
公共静态隐运营商学生(字符串名称)
{
返回新学生
{
名称=名称
};
}
}
然后,你可以做学生学生=萨布丽娜;
i know that string is like a class, and when creating a new string the string itself doesnt owe the value but only the value's pointer. but when creating a string there is no need to use the word new;
string a = "hello";
and not
string a = new string("hello");
I know that the second option is also possible but what i want to understand is why the first one?
Let's say I have a class name student which he's constructor gets a string
. To create a new class I must use the saved word new.
student example = new student("Sabrina");
I tried overload oparator =
but it is not possible.
How can I create a new class like a string
does (without using the word new
)?
student example = "Sabrina";
You can use cast operator to implicitly:
sealed class Student
{
public string Name
{
get;
private set;
}
Student()
{
}
public static implicit operator Student(string name)
{
return new Student
{
Name = name
};
}
}
Then you can do Student student = "Sabrina";
.
这篇关于如何调用构造函数没有新的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!