如何调用构造函数没有新的? [英] How to call constructor without new?

查看:104
本文介绍了如何调用构造函数没有新的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道该字符串就像是一个类,并创建一个新的字符串时字符串本身犯规欠的价值,但只有价值的指针。但创建一个字符串时,有没有必要使用新词;

 字符串=你好; 



而不是

 串=新的字符串(你好); 



我知道,第二个选项也有可能,但我想知道究竟是为什么第一个?



让我们说我有一个类名的学生,他的构造得到了字符串。要创建一个新的类,我必须使用保存的新词

 学生例如=新的学生(萨布丽娜); 



我试过超载算符= ,但它是不可能的。



我怎样才能创建像字符串的新类做(不使用这个词)?

 学生例如=萨布丽娜; 


解决方案

您可以使用转换操作符隐式:

 密封类学生
{
公共字符串名称
{
搞定;
私人集;
}

学生()
{
}

公共静态隐运营商学生(字符串名称)
{
返回新学生
{
名称=名称
};
}
}



然后,你可以做学生学生=萨布丽娜;


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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆