[英]How to create a method that takes a generic class as a parameter
I've been searching SO and elsewhere for an answer to this question, and I can't find one that is helping me understand my problem. 我一直在搜索SO和其他地方寻找这个问题的答案,我找不到能帮助我理解我的问题的答案。 I'm new to C#, so that might be part of the issue. 我是C#的新手,所以这可能是问题的一部分。
I'm trying to get a handle on how to pass a class (or a copy of one) as a parameter to a method. 我试图了解如何将一个类(或一个副本)作为参数传递给方法。 However, I want this method to accept any class I pass it, not a specific one. 但是,我希望这个方法接受我传递的任何类,而不是特定的类。
So for instance: 例如:
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"
}
Okay, I know that above syntax isn't correct insofar as passing those classes as parameters or in accepting them as arguments for the method, but I'm hoping that you can see what I'm trying to do. 好吧,我知道上面的语法是不正确的,只要将这些类作为参数传递或接受它们作为方法的参数,但我希望你能看到我正在尝试做的事情。 I'd like to be able to pass any class deriving from Person to the SayName method, and have it output whatever its name happens to be. 我希望能够将任何派生自Person的类传递给SayName方法,并让它输出其名称恰好是什么。
Thanks in advance, any help is appreciated. 在此先感谢,任何帮助表示赞赏。
Is there a way to do this? 有没有办法做到这一点?
Just pass them as Person
: 只需将它们作为Person
传递:
static public void SayName(Person person1, Person person2)
{
Console.WriteLine(person1.Name + ", " +person2.Name) // I'd like this to output "Bob, Fred"
}
Type is not declared as parameters in SayName, seems to be a misunderstanding in understanding how to pass parameters. Type未在SayName中声明为参数,似乎是在理解如何传递参数时的误解。 Use Person type for both parameters say person1 and person 2 the code will run 使用两个参数的人员类型说出代码将运行的person1和person2
public static void SayName(Person person1, Person person2)
{
Console.WriteLine(person1.Name + ", " +person2.Name)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.