简体   繁体   English

C#如何对泛型类型的两个类使用一种方法?

[英]C# How to use one method for two classes with Generic type?

I need to merge two different print method into one. 我需要将两种不同的打印方法合并为一种。 I have two generic classes and my own generic list class. 我有两个通用类和我自己的通用列表类。 Let's say I have 假设我有

static void Print(string fv, MyListClass<Module> A,
            string top)
 and static void Print2(string fv, MyListClass<Student> A,
            string top)

Inside of the method is the same, but how to make them to be one method and in Main class I choose in parameters which one class list am I printing, Module either Student. 方法的内部是相同的,但是如何使其成为一种方法,并且在Main class中我选择要打印的是一个类列表的参数,或者Module或Student。 My data is in: 我的数据在:

MyListClass<Student> Stud; 
MyListClass<Module> Mod;

I have two generic classes and my own generic list class. 我有两个 通用 类和我自己的通用列表类。

Why do you have your own list class? 您为什么有自己的列表类? You generally shouldn't. 您通常不应该。 Assuming it implements IEnumerable<T> : 假设它实现IEnumerable<T>

Let both Module and Student implement a common interface with the properties you want to print, say IPrintable : ModuleStudent使用要打印的属性实现一个公共接口,例如IPrintable

public interface IPrintable
{
    string Name { get; }
    string Description { get; }
}

public class Module : IPrintable { ... }
public class Student : IPrintable { ... }

Now create a method with a generic parameter: 现在创建一个带有通用参数的方法:

void Print<T>(string fv, IEnumerable<T> A, string top)
    where T : IPrintable
{
    foreach (var item in A)
    {
        Console.WriteLine(item.Name + ": " + item.Description);
    }
}

为此,您只需创建一个基类,从中派生Module和Student类,然后在单个方法的签名中使用基类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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