Constructor overload contains already defines a member with the same signature

浪尽此生 提交于 2021-02-17 05:50:28

问题


public Module(string a, object obj) : this(a, null, obj) { }

public Module(string b, object obj) : this(null, b, obj) { }

These constructor overloads do not work

'already defines a member with same parameter types'

I have looked around and realise that I cannot do this in c# but can anyone suggest a way around this?

Edit: Thanks for answers.

In this case I have decided that to go with this for now:

public Module(string a, object obj) : this(a, null, obj) { }

public Module(string a, string b, object obj) : this(a, b, obj) {}

So users will have to include a if they want to use b... not brilliant but there you go


回答1:


Parameter names are meaningless in the context of overloads. I can see what you are trying to do, but I'm not sure why. I would dispense with it entirely:

public Module(string a, string b, object obj){}

Then call the Module constructor, passing in null values as appropriate.

Module m = new Module(null, "hi", obj);

Module m2 = new Module("bye", null, obj);



回答2:


personally i use optional arguments:

public Module(object obj, string a = null,string b = null) : this(a, b, obj) { }

Heres an article on what they are and how to use them, Note though they are only avaliable in VS2010 (they are part of the compiler not the language so they are available in .net 3.5 as well as 4.0) http://msdn.microsoft.com/en-us/library/dd264739.aspx




回答3:


It's just not possible. You should remove those two constructor overloads.

However, you could work with static factory methods instead. Make sure to use clear names to convey the difference to the API consumer.

static Module CreateA(string a, object o) { return new Module(a, null, o); }
static Module CreateB(string b, object o) { return new Module(null, b, o); }


来源:https://stackoverflow.com/questions/8969523/constructor-overload-contains-already-defines-a-member-with-the-same-signature

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!