How to call constructor without new?

后端 未结 4 783
夕颜
夕颜 2021-01-20 17:50

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

4条回答
  •  北恋
    北恋 (楼主)
    2021-01-20 18:54

    Although you can get this done using an implicit operator, I would highly recommend not doing this at all. Strings are special animals in C# and they get special treatment - along with other special classes like int and float, you can create them without explicitly newing them up due to the way the C# compiler works:

    var myInt = 0;
    var myFloat = 0f;
    var myString = "string";
    

    However, this behavior is typically restricted to those special classes. Adding an implicit operator to do this is bad practice for multiple reasons:

    • It hides what is actually going on underneath. Are we creating a new Student under the hood when converting from a string?
    • It is unmaintainable. What happens when you have to add another parameter to the constructor to include the Student's ID number as well?
    • It eliminates the possibility of using implicitly-typed variables. You can't call var student = "name"; you must call Student student = "name".

    The implicit operator paradigm breaks down very quickly. Though it's a cool thing to do, you're setting yourself up for a bad time down the road and making your code more difficult to read. I would highly advise just using new Student("name") like all other normal objects in C#.

提交回复
热议问题