刚开始学习C#,需要用到DLL,看网上资料,借用前辈的例子,自己搞了搞:
C#中生成DLL
1.选择New Project中的C#, Class Library, 命名MyDll
2.打开Class1.cs, 在namespace MyDll中添加public class CSwap; public class CMaxCD.
3.在CSwap中添加public static bool Swap(ref long i, ref long j);
在CMaxCD中添加public static long MaxCD(long i, long j);
4.存盘, Build MyDll.
C#中调用DLL
1.选择New Project ->C#->Console Application,命名MyDllApp
2.在Program.cs中添加using MyDll. 在project中选择add references,选择MyDll.dll。
3.在main()中就可以调用Dll中的函数了。
Class1.cs代码
using System;
using System.Collections.Generic;
using System.Text;
namespace MyDll
{
public class CSwap
{
public static bool Swap(ref long i, ref long j)
{
//
// TODO: Add constructor logic here
//
i = i + j;
j = i - j;
i = i - j;
return true;
}
}
public class CMaxCD
{
public static long MaxCD(long i, long j)
{
//
// TODO: Add constructor logic here
//
long a, b, temp;
if (i > j)
{
a = i;
b = j;
}
else
{
b = i;
a = j;
}
temp = a % b;
while (temp != 0)
{
a = b;
b = temp;
temp = a % b;
}
return b;
}
}
}
Program.cs代码
using System;
using System.Collections.Generic;
using System.Text;
using MyDll;
namespace MyDllApp
{
class Program
{
static void Main(string[] args)
{
if (args.Length != 2)
{
Console.WriteLine("Usage: MyClient<Num1><Num2>");
return;
}
long num1 = long.Parse(args[0]);
long num2 = long.Parse(args[1]);
CSwap.Swap(ref num1, ref num2);
Console.WriteLine("The result of Swap is num1= {0} and num2= {1}", num1, num2);
long maxcd = CMaxCD.MaxCD(num1, num2);
Console.WriteLine("The MaxCD of {0} and {1} is {2}", num1, num2, maxcd);
Console.ReadKey();
}
}
}
文章评论(0条评论)
登录后参与讨论