繁体   English   中英

C#当类的类型为Generic时,如何访问类的元素? [重复]

[英]C# How do i access an element of a class when the type of class is Generic? [duplicate]

可能重复:
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;
}

在此先感谢您提供的所有帮助!

您可能想要这样的东西:

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类源自有机体,在构造时将Found设置为true
  • CountFound方法在T上具有通用约束(where子句),指定它必须源自有机体(满足此条件的事物)。 然后,您可以使用Organism在该方法中提供的任何方法或属性-在本例中为Organism.Found。

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

假设接口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; }
}

您的课程必须实现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);

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

如果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的时候T是(或继承) Something ,那么这就是简单的:

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;
}

在您的方案中,您似乎不想尝试实现一个相等函数,因为相等总是在您正在比较的类型的上下文中定义的(每种类型都需要特定的代码进行比较)。 如果您所有的T都是通用类型(基类),并且相等条件可以用基类的通用属性等表示,则这对您有用。

暂无
暂无

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

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