问题
Apparently optional parameters won't work in C# Xna when used on the Xbox, there non suportedness is stated during compilation.
I have a situation like this:
func(float? a = null, int? b = null)
With large numbers of thease optional parameters that default to the "undefined" value, null. This situation is required.
In the simplified example above this can be unwrapped, although this isn't as optional parameters allow:
func()
func(float? a)
func(int? b)
func(float? a, int? b)
However with large numbers of parameters this isn't practical.
Some combinations of parameters definedness isn't permitted and results in paths through the function where I throw argument exceptions, others result in various different things occurring depending on the values of the parameters. This is similar to polymorphism between functions with the same name but is not the same.
I could alternatively, and probbably most practically, require all the parameters instead.
func(float? a, int? b)
Then call as so:
func(null, 4)
Where the first is undefined.
Instead of using one of the above bodges, is there a way to enable optional parameters in C# XNA on Xbox?
回答1:
I've certainly run on the XBOX with optional parameters, but it required some tweaking of the build settings. From what I recall it will not work with WP7 however.
I think it might have been related to the Language Version being used.
Check out the following links:
http://msdn.microsoft.com/en-us/library/ff827884.aspx
http://forums.create.msdn.com/forums/p/54007/327944.aspx
回答2:
I would use old-fashioned overloads that take different numbers of parameters, and forward the calls on from there, along with the "default" values. Zero code changes to the callers.
If the types are outside your control: extension methods to add the overloads.
回答3:
I don't think you can enable the optional parameters. Maybe you can use an alternative. like the params keyword that creates an array, you could just pass an object as parameter
public class MyParams
{
public float? a {get;set;}
public int? b {get;set;}
}
func(new MyParams { b = 5 });
With that solution, you have all the flexibility you might want. You can add, remove parameters without thinking of adding/removing new overload. And if you remove or edit a parameter, you'll get a compile time error, something you might not get with multiple overload.
来源:https://stackoverflow.com/questions/9502507/c-sharp-xna-xbox-in-this-case-optional-parameters-are-not-optional