Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
73 views
in Technique[技术] by (71.8m points)

c# - How can I add a default constructor and have it call another constructor and use the default values?

I have this code:

public class NewFrame 
{

    public NewFrame(string iconSource = Const.Car,
        string iconColor = Const.Red)
    {

When I try and use it then it's telling me I am missing a default constructor. How can I add one of these and still make the code use the default values for iconBackgroundColor and IconSource? I thought that adding in those defaults with the = Const. would make it work but it seems like it doesn't think my constructor is a default (with no params).

question from:https://stackoverflow.com/questions/65650321/how-can-i-add-a-default-constructor-and-have-it-call-another-constructor-and-use

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

By having two optional parameters, you don't actually create 4 different constructor declarations under the hood (one with both parameters, one with the first parameter, one with the second parameter, and one with neither). There is still only one constructor, with two parameters. It's just that C# recognises that the parameters are optional, and has syntactic sugar to let you omit them when you call the constructor.

However, if you use reflection to create an instance of your class (probably whatever the thing that requires a default constructor is doing), and you attempt to invoke the parameterless constructor, it won't find one, because there is no syntactic sugar in reflection.

Here is an example:

class MainClass
{
    public static void Main(string[] args)
    {
        Type t = typeof(MainClass);
        object o = Activator.CreateInstance(t, 1);
        Console.WriteLine(o);
    }

    public MainClass(int a = 10)
    {

    }
}

If you use typeof(MainClass).GetConstructors(), it will tell you that there is only one.

To actually declare a default constructor, you can do:

public class NewFrame 
{

    public NewFrame(string iconSource = Const.Car,
        string iconColor = Const.Red)
    {
        ...
    }

    public NewFrame() : this(Const.Car, Const.Red) {  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...