Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

c# - Can a method be attached to a delegate with predefined parameters?

Sometimes I encounter cases where I have to attach a method to a delegate but the signature doesn't match, like trying to attach abc down there to somedelegate with the string parameter being "hi".

public class test
{
   //...
   public void abc(int i, string x)
   {
      //Do Something
   }
   //...
}
public class test2
{
   somedelegate x;
   //...
   public test2()
   {
      //Do Something
      test y = new test();
      x += y.abc(,"hi");
   }
   delegate void somedelegate(int i);
}

I can work it around by creating another delegate with the correct signature then attaching it but it seems so unnecessarily complex. Can you do something like this in C#? Thanks.

EDIT: I guess there closest to what I wanted to achieve is:

x += (int i) => abc(i, "hi");
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just Googling for '.net delegate optional parameters' returns some results that may be useful:

Update (researching this some more, and helped by the first link above):

Could you perhaps use the Invoke method, which accepts any delegate?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...