简体   繁体   中英

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. I'm new to C#, so that might be part of the issue.

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.

Thanks in advance, any help is appreciated.

Is there a way to do this?

Just pass them as 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. Use Person type for both parameters say person1 and person 2 the code will run

public static void SayName(Person person1, Person person2)
{
    Console.WriteLine(person1.Name + ", " +person2.Name)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM