C#当类的类型为泛型时,我如何访问类的元素

本文关键字:何访问 元素 访问 类型 泛型 | 更新日期: 2023-09-27 17:50:32

可能重复:
C#如果两个对象的类型相同,我该如何比较它们?

我有一个通用函数,

class Something {
    public int found;
    public Something() {
        this.found = true;
    }
}
List<Something> something;
public int countFound<T>(List<T> Organisms)
{
    if (typeof(T) == typeof(Something))
    {
        foreach (T organism in Organisms)
        {
            // here i want to check something like organism.found == true how do i do it?
        }
    }
    return 0;
}

提前感谢您的帮助!

C#当类的类型为泛型时,我如何访问类的元素

您可能想要这样的东西:

class Organism
{
    public bool Found
    {
        get;
        set;
    }
}
class Something : Organism
{
    public Something()
    {
        this.Found = true;
    }
}
public class Program
{
    public int countFound<T>(List<T> Organisms)
        where T : Organism
    {
        foreach (T organism in Organisms)
        {
            if (organism.Found)
            {
                // Do something with the organism
            }
        }
        return 0;
    }
}

这里的关键点是:

  • 您有一个名为Organism的公共基类,它定义了Found属性
  • Something类源自Organism,在构建时将Found设置为true
  • CountFound方法在T上有一个通用约束(where子句(,指定它必须派生自Organism(Something符合此标准(。这样就可以使用Organism在方法中提供的任何方法或属性——在本例中为Organism.Found

这里有两个选项,具体取决于您希望函数执行的操作:

如果countFound函数必须采用所有类型T,但当T是(或继承自(Something时,您需要特殊情况,则可以使用以下方法:

public int countFound<T>(List<T> Organisms)
{
    if (typeof(T) == typeof(Something) || typeof(T).IsSubclassOf(typeof(Something)))
    {
        foreach (T organism in Organisms)
        {
            Something s = (Something)(object)organism;
            // do whatever you like with s
        }
    }
    return 0;
}

如果当T是(或继承自(Something时,希望函数采用类型T,那么这更简单:

public int countFound<T>(List<T> Organisms) where T : Something
{
    foreach (T organism in Organisms)
    {
        // here organism will have all of the properties of Something
    }
    return 0;
}

您必须将泛型限制为一个(或多个(接口,该接口指示实现泛型所需的属性!

假设接口IFound实现了您想要检查的属性:

public int countFound<T>(List<T> Organisms) where T : IFound
{     
    if (typeof(T) == typeof(Something))     
    {         
         foreach (T organism in Organisms)         
         {
              if(organism.found)) // done because IFound tells T has a property with this name
         }
    }     
    return 0; 
} 

IFound是一个必须自己实现的接口。例如:

interface IFound
{
    bool Found { get; }
}

你的类Something必须实现IFound:

class Something : IFound
{
    public bool Found
    {
        get { return true; } // implement your condition in a method called here
    }
}

然后你可以像你想要的那样调用你的方法:

int a = countFound<Something>(List<Something> parameter);

在您的场景中,您似乎不想尝试实现相等函数,因为相等总是在您正在比较的类型的上下文中定义的(每个类型执行比较的特定代码(。如果所有的T都是一个公共类型(基类(,并且相等条件可以用基类的公共属性等来表示,那么这将适用于您。