c# - 如何创建一个将泛型类作为参数的方法

标签 c#

我一直在 S.O 和其他地方寻找这个问题的答案,但找不到可以帮助我理解我的问题的答案。我是 C# 的新手,所以这可能是问题的一部分。

我正在尝试了解如何将类(或类的副本)作为参数传递给方法。但是,我希望此方法接受我传递给它的任何类,而不是特定类。

例如:

class Person
{
    public string Name{ get;set; }
}

class Bob : Person
{
    public Bob(){ Name = "Bob"; }
}

class Fred : Person
{
    public Fred(){ Name = "Fred"; }
}

Fred aFred = new Fred();
Bob aBob = new Bob();

// below is where I need the help, I don't know the syntax for what I'm trying to do.
SayName(aBob,aFred);

static public void SayName(person1,person2)
{
    Console.WriteLine(person1.Name + ", " +person2.Name) // I'd like this to output "Bob, Fred"
}

好的,我知道上述语法在将这些类作为参数传递或接受它们作为方法的参数方面是不正确的,但我希望您能看到我正在尝试做的事情。我希望能够将从 Person 派生的任何类传递给 SayName 方法,并让它输出它的名称。

在此先感谢您的帮助。

有没有办法做到这一点?

最佳答案

只需将它们作为 Person 传递:

static public void SayName(Person person1, Person person2)
{
    Console.WriteLine(person1.Name + ", " +person2.Name) // I'd like this to output "Bob, Fred"
}

关于c# - 如何创建一个将泛型类作为参数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22518538/

相关文章:

c# - .NET 3.5 的 Javascript : How to give textbox focus after a pop-up is closed

c# - 在将文件流式传输给用户时在 ASP.NET(通过服务器)中下载文件

c# - 如何将弱类型 JSON 转换为 C# 可读对象

c# - 在 C# 中,当一个字段可能是字符串或字符串数​​组时,如何反序列化此 json?

c# - XAML数据绑定(bind),对象与目标类型不匹配

c# - 创建的性能计数器不可见

c# - 如何将参数传递给 IN 运算符?

c# - 调用lambda时 "DisplayClass"name是什么意思?

c# - 如何将正文中的null传递给asp.net core 3.1中的终结点

c# - 通过对象中的 IDictionary<string,object> 属性选择不同记录