Alternatives to optional (VB) parameters in C#?
I have been told that there is no such thing as optional parameters in C#. But you can use overload functionality and input varibles with default values such as:
void Person(string name, 开发者_如何学运维int age)
void Person(string name)
and
void Person(string name, int age = 30)
My problem is that when calling C# components from VB6 overloaded methods tends to change name to for example "Person(string name), Person_1(string name, int age)" etc, and variables with default values can't be used when beeing "out" variables.
BUT how about
void Person(string name, [Optional] int age)
??
Can someone explain to me how that work and if i can use it to simulate optional variables in VB6?
As of C# 4, there is optional parameter support:
public void MyMethod(bool arg = false)
{
}
Not sure how this would get called from VB6 though.
Another possible way is to wrap the arguments in another class:
public class PersonSettings
{
public string Name { get; set; }
public int Age { get; set; }
}
public Person(PersonSettings settings)
{
}
You then have one argument and can default values in the PersonSettings
class as needed.
Of course, your proposed use of the OptionalAttribute
should also work for you. Though I think you need to get rid of the overloaded method, or use an interface to only expose one of those methods to COM:
http://social.msdn.microsoft.com/Forums/en/clr/thread/048c0104-20ed-49af-a221-ddadb081989e
C# 4.0 does indeed have optional parameters:
public void MyMethod(string optionalParameter = "optional")
{
}
I sorted this out by using OptionalAttribute
. I think this was the best solution because all the other solutions would have been to timeconsuming and comprehensive.
To check if an optional attribute was passed, use: if(attr_optional != Type.Missing)
(requires that the optional attribute is of type object
)
You can do this:
void Person(string name, int? age)
{
if (!age.hasValue)
{
Console.WriteLine("The nullable integer parameter age wasn't provided with a value ..");
}
}
You'll have to send "null" instead of an int, though. Empties won't work.
精彩评论