问题
Suppose I have these two ctors:
public SomeClass(string a, Color? c = null, Font d = null)
{
// ...
}
public SomeClass(string a, Font c = null, Color? d = null)
{
// ...
}
~and I do this:
SomeClass sc = new SomeClass("Lorem ipsum");
I'll get this: "Error 1 The call is ambiguous between the following methods or properties [...]"
It seems apparent to me that it doesn't matter which one I refer to as the end result is the same (at least in this particular case, and to me that's all that matters right now), so what are my options to getting around this?
EDIT 1: @oltman: Simplified example.
I just want to be able to write
[...] new SomeClass("Lorem", Color.Green)
instead of
[...] new SomeClass("Lorem", null, Color.Green)
回答1:
Both constructors take the same number of arguments, but in a different order. Since you have specified default values for the two constructor parameters the compiler cannot distinguish between the two overloads when the second argument is not supplied.
I would advise you to remove the existing constructors and replace with the following:
public SomeClass(string a, Color? color, Font font)
{
// constructor implementation
}
public SomeClass(string a) : this(a, null, null) {}
public SomeClass(string a, Color color) : this(a, color, null) {}
public SomeClass(string a, Font font) : this(a, null, font) {}
回答2:
One way to force it to work:
SomeClass sc = new SomeClass("Lorem ipsum", (Color?)null, (Font)null);
回答3:
This is a perfect example of anti-pattern
, the best way avoiding this is @Phil Klein's answer.
Here is another syntax for passing class as null:
SomeClass sc = new SomeClass("Lorem ipsum", null as Color, null as Font);
回答4:
Can you create another constructor that takes just the string, and update the above constructors to make their second parameters mandatory?
If the idea is that you can construct the object by always supplying the string and then optionally supplying color or font or both, how about this:
public SomeClass(string a)
{
// ...
}
public SomeClass(string a, Color? c)
{
// ...
}
public SomeClass(string a, Font f, Color? d = null)
{
// ...
}
回答5:
I'll get this: "Error 1 The call is ambiguous between the following methods or properties [...]"
It seems apparent to me that it doesn't matter which one I refer to as the end result is the same
The call is ambiguous. Each constructor is unique - it doesn't matter if they both create and return an instance, because there could be different logic in each constructor. The compiler still doesn't know which constructor you mean.
来源:https://stackoverflow.com/questions/8845494/the-call-is-ambiguous-between-the-following-methods-or-properties