我们有为什么在C#中使用构造函数的方法?请举个例子? [英] We have methods why we are using constructors in C#? Please give me an example?

查看:165
本文介绍了我们有为什么在C#中使用构造函数的方法?请举个例子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

we have methods why we are using constructors in c#





我尝试过:





What I have tried:

we have methods why we are using constructors in c#? please give real time example ?

推荐答案

类可能是一件复杂的事情:暂时考虑一下Form。它是一个类,但它是一个需要在准备好使用之前完成许多复杂事情的类 - 查看Designer.cs文件并查看InitializeComponent正在做多少工作。



如果你没有构造函数,那么每次构造一个表单实例时都必须手动完成所有这些操作,这意味着存在遗忘某些东西的高风险,并且很有可能重复代码 - 这使得维护更加困难,从而降低了可靠性。



因此,构造函数可以在首次使用之前设置类实例,以便在需要时该课程将准备好运行。



您不必使用它们 - 如果您不创建构造函数系统将为您创建一个空的无参数 - 您可以创建对象,其中调用构造函数是完全可选的。如果你创建一个 struct 而不是,那么即使你提供了一个构造函数,它也不会被调用,除非<使用code> new 关键字:

A class can be a complex thing: think about a Form for a moment. It's a class, but it's a class which requires a lot of complicated things to be done before it's ready to be used - have a look in your Designer.cs file and look at how much work InitializeComponent is doing.

If you didn't have constructors, you would have to manually do all that every time you constructed a form instance, and that means both that there is a high risk of "forgetting" something, and a good chance of duplication of code - which makes maintenance harder, and thus reduces reliability.

So Constructors are there to set up your class instance before it is first used, in order that the class will be "ready to run" when it is needed.

You don't have to use them - if you don't create a constructor the system will create an empty parameterless one for you - and you can create objects where calling the constructor is completely optional. If you create a struct instead of a class, then even if you provide a constructor it is not called unless the new keyword is used:
public struct MyStruct
    {
    public int I;
    public string S;
    public MyStruct(int i)
        {
        I = i;
        S = "Goodbye";
        Console.WriteLine("MyStruct Constructor");
        }
    }




MyStruct ms1;                          // Constructor not called.
ms1.I = 666;
ms1.S = "Hello";
MyStruct ms2 = new MyStruct(333);      // Constructor called
Console.WriteLine("{0}:{1}", ms1.I, ms1.S);
Console.WriteLine("{0}:{1}", ms2.I, ms2.S);


我想说在构造函数中将事物设置为默认值而不必调用某些方法会很方便。

请参阅此处的示例: https://www.dotnetperls.com/constructor [ ^ ]

但是如果你不喜欢构造函数,请不要使用它们: )
I would say it is just convenient to setup things to a default value in a constructor without having to call some method.
See examples here: https://www.dotnetperls.com/constructor[^]
But if you don't like constructors, don't use them :)


构造函数可以强制user提供正确实例化该类所需的参数。



这是另一种形式依赖注入。
Constructors can force the "user" to supply parameters required for the proper instantiation of that class.

It's another form of "dependency injection".


这篇关于我们有为什么在C#中使用构造函数的方法?请举个例子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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