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

Categories

I'm trying to create a delegate of a static method which takes a ref argument. Please don't ask why I'm doing such a cockamamie thing. It's all part of learning how .Net, C#, and reflection work and how to optimize it.

My code is:

    public struct DataRow
    {

        private double t;
        static public void Cram_T(ref DataRow dr, double a_t)
        {
            dr.t = a_t;
        }
    }
 ''''
  Type myType = typeof(DataRow);
  MethodInfo my_Cram_T_Method = myType.GetMethod("Cram_T");
  var myCram_T_Delegate = 
         Delegate.CreateDelegate(typeof(Action<DataRow, Double>),      
                                 my_Cram_T_Method) 
                                 as Action<DataRow, Double>;

This gives me a binding error because (I think) the generic action doesn't match the method.

Inspecting the value of Cram_T_Method in the watch window gives

{Void Cram_T(DataRow ByRef, Double)}

I then tried using the ref keyword in the Action:

  var myCram_T_Delegate = 
         Delegate.CreateDelegate(typeof(Action<ref DataRow, Double>),         
                                 my_Cram_T_Method) 
                                 as Action<ref DataRow, Double>;

But this won't compile. The C# compiler chokes at the token "ref".

What is the right way to create this delegate?

See Question&Answers more detail:os

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

1 Answer

Create your own delegate type:

delegate void MyAction(ref DataRow dataRow, double doubleValue);

And use MyAction in place of Action<ref DataRow, Double> -- which, as you've noted, doesn't compile.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...