开发者

Parameters with no identifiers in C#?

In C++ it is possible to skip method parameter identifier if it's unused:

void foo( int, int ) {}

This is very useful in case o开发者_开发问答f interface implementations where a huge number of method has empty body. Is it possible to do something similiar in C#? Straight test gives error:

public void OnAddInsUpdate( ref Array )  {} // Error, need identifier :(


Afraid not - take a look at the language spec here:

  • http://msdn.microsoft.com/en-us/library/aa645760%28VS.71,classic%29.aspx
  • http://msdn.microsoft.com/en-us/library/aa645761%28VS.71%29.aspx


I don't believe this is possible. If you have unused parameters you should probably consider overloading or named parameters (new in C# 4.0).


This is not supported by the C# language.


It's not possible in C# you need to provide the parameter name, however, I don't see what's wrong with a check in the method to see if it has been set e.g.

public void OnAddInsUpdate(int x, int? y)
{
     // do something with x
     if (y != null)
        // do something with y
}

C# 4.0 introduces Optional Parameters.


Your example of an event with a number of arguments should actually be done using EventArgs.

This has a number of benefits. The primary one being that you can pass through a large number of potential values, but only populating the ones relevant.

The additional benefit is that you can at a later stage add more values without altering the signature of the event, and requiring all consumers to be updated.

So, for instance:

 public void OnAddInsUpdate(AddInsUpdateEventArgs e)  { } 

 public class AddInsUpdateEventArgs : EventArgs 
 { 
    public int x { get; }  // Readonly for event handler
    public int? y { get; set; }  // Read/Write (eg if you can accept values back) 
    public bool? Handled { get; set; } 
 } 


Maybe the use of params will give you what you want:

public class MyClass 
{

   public static void UseParams(params int[] list) 
   {
      for ( int i = 0 ; i < list.Length ; i++ )
         Console.WriteLine(list[i]);
      Console.WriteLine();
   }

   public static void UseParams2(params object[] list) 
   {
      for ( int i = 0 ; i < list.Length ; i++ )
         Console.WriteLine(list[i]);
      Console.WriteLine();
   }

   public static void Main() 
   {
      UseParams(1, 2, 3);
      UseParams2(1, 'a', "test"); 

      int[] myarray = new int[3] {10,11,12};
      UseParams(myarray);
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜