在我的主要类'A'中,我声明了一个函数和委托来调用该函数,我想将我的委托传递给另一个类'B',但是B类将如何知道委托是什么类型的?
A级
public delegate void SendInfo(string[] info);
SendInfo sendInfo = new SendInfo(SendInformation); //I have a function SendInformation
B b = new B();
b.SetDelegate(sendInfo);
Run Code Online (Sandbox Code Playgroud)
B级
public delegate void SendInfo(string[] info); //I know this is wrong but how will
SendInfo SendInformation; //this class know what SendInfo is?
public void SetDelegate(SendInfo sendinfo) //What type is this parameter?
{
sendinfo.GetType();
SendInformation = sendinfo;
}
Run Code Online (Sandbox Code Playgroud)
谢谢,
埃蒙·
Kie*_*one 10
当你在类A中声明委托'in'时,你将它声明为类A的子类型.所以它的类型ClassA.SendInfo
是例如.在B级你可以使用
public void SetDelegate(ClassA.SendInfo sendinfo)
Run Code Online (Sandbox Code Playgroud)
或者,在类A的代码之外声明委托 - 然后它将只是您可以通过name(SendInfo
)引用的另一种类型.
Jon*_*eet 10
为什么要声明具有相同签名的两个单独的委托类型?声明一个单一的委托类型(如果你真的要-使用Func
和Action
家庭,可能的话)任何其他类外,并使用它无处不在.
你写的时候需要注意:
public delegate void SendInfo(string[] info);
Run Code Online (Sandbox Code Playgroud)
这真的是声明一个类型 - 你可以直接在命名空间中声明该类型; 它不必是另一种类型的成员.
归档时间: |
|
查看次数: |
18225 次 |
最近记录: |