可能重复:
C# how do I compare two objects if they are of same type?
我有一个通用函数,
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;
}
提前感谢所有帮助!
答案 0 :(得分:2)
你可能想要这样的东西:
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;
}
}
这里的关键点是:
答案 1 :(得分:1)
您必须将通用限制为一个(或多个)接口,该接口要求实现通用所需的属性!
假设接口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);
答案 2 :(得分:1)
这里有两个选项,具体取决于您希望函数执行的操作:
如果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;
}
答案 3 :(得分:0)
在您的场景中,您似乎不想尝试实现相等函数,因为相等性总是在您要比较的类型的上下文中定义(每种类型的特定代码进行比较)。如果所有T
都是一个普通类型(基类),并且相等条件可以用基类的公共属性等表示,那么这对你有用......