C# 在C中声明了两个相同的变量
我在网上找到了一个我在程序中使用的代码,但令我惊讶的是,我发现有一个变量/函数声明了两次 现在,如果我要向DLL发送任何值,我将向这两个值中的哪一个发送信息? 一个用完了,而第二个没有。。。 见代码:C# 在C中声明了两个相同的变量,c#,out,C#,Out,我在网上找到了一个我在程序中使用的代码,但令我惊讶的是,我发现有一个变量/函数声明了两次 现在,如果我要向DLL发送任何值,我将向这两个值中的哪一个发送信息? 一个用完了,而第二个没有。。。 见代码: [DllImport("msman.dll", CallingConvention=CallingConvention.StdCall, CharSet=CharSet.Ansi, ExactSpelling=false)] public static extern bool re
[DllImport("msman.dll", CallingConvention=CallingConvention.StdCall, CharSet=CharSet.Ansi, ExactSpelling=false)]
public static extern bool receive(int ID, double[] Bid, double[] Ask);
public bool receive(int ID, out double first, out double second)
{
bool flag;
double[] Array1st = new double[1];
double[] Array2nd = new double[1];
if (Form1.receive(ID, Array1st, Array2nd))
{
first = Array2nd[0];
second = Array1st[0];
flag = true;
}
else
{
second = 0;
first = 0;
flag = false;
}
return flag;
}
还有,为什么可以声明两个变量呢?我的C不是很好,但这看起来像是 注意每个方法的签名
A: public static extern bool receive(int ID, double[] Bid, double[] Ask);
B: public bool receive(int ID, out double first, out double second)
A采用以下参数:int、double[],double[]
而B取int,double,double。注意类型的不同。所以当你调用它时,编译器会说,哦,你想用一个int和两个双数组来调用receive。明白了,给你!并提供了一个
调用如何工作的示例:
int x = 1; double y = 1.0; double z = 2.0;
receive(x, y, z); // <-- this calls the second method (B).
int x = 1; double[] y = new double[1]; double[]z = new double[1];
y[0] = 1.0;
z[0] = 1.0;
receive(x, y, z); // <-- this calls the first method (A)
方法可以重载,也就是说,只要参数不同,它们可以具有相同的名称。不允许仅对返回类型重载
因此,这是有效的:
void Foo(int x) { }
void Foo(char x) { }
或者,在您的情况下:
bool receive(int ID, double[] Bid, double[] Ask);
bool receive(int ID, out double first, out double second)
注意到这是许多其他语言的标准语言特征,包括C++。
方法重载是面向对象的概念,方法可以同名,只有参数的方法不同。 using System;
class Test
{
static void receive(int x, double y)
{
Console.WriteLine("receive(int x, double y)");
}
static void receive(double x, int y)
{
Console.WriteLine("receive(double x, int y)");
}
static void Main()
{
receive(5, 10.2);
}
}
请参见此处虽然名称相同,但参数不同。编译器就是这样知道使用哪一个的。你的意思是我可以向其中任何一个发送值吗?可能是@user2864740的重复。如果签名完全相同,我不确定静态是否有效重载。@GSerg,你错了。。。这不是一个重复的链接,因为他们都要求两个不同的东西…是的,绝对。这是方法重载的直接例子。哇!,你的解释令人难以置信。。因为,我正在寻找一种向函数发送值的方法,自从。。。