C#需要设计一个方法,用于向某人问好,并且要支持各个国家的人使用,具有可扩展性,使用委托技术
时间: 2023-07-30 10:08:01 浏览: 124
可以使用委托技术来实现该方法,并支持多语言问候。以下是一个简单的示例代码:
```csharp
using System;
delegate string GreetingDelegate(string name);
class Greeting
{
private GreetingDelegate greetingDelegate;
public Greeting(GreetingDelegate greetingDelegate)
{
this.greetingDelegate = greetingDelegate;
}
public void SayHello(string name)
{
Console.WriteLine(greetingDelegate(name));
}
}
class Program
{
static void Main()
{
Greeting englishGreeting = new Greeting(delegate (string name) {
return $"Hello, {name}!";
});
Greeting chineseGreeting = new Greeting(delegate (string name) {
return $"你好,{name}!";
});
englishGreeting.SayHello("John");
chineseGreeting.SayHello("张三");
}
}
```
该代码定义了一个 `GreetingDelegate` 委托类型,用于传递不同语言的问候语。然后定义了一个 `Greeting` 类,该类接收一个 `GreetingDelegate` 委托实例,并提供了一个 `SayHello` 方法来向某人问好。在 `Main` 方法中,我们创建了两个不同语言的 `Greeting` 实例,并调用 `SayHello` 方法来输出问候语。你可以通过添加更多的委托实例来支持更多的语言。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)