为什么智能感知不能在我的Generic上工作?
本文关键字:工作 Generic 我的 智能 感知不能 为什么 | 更新日期: 2023-09-27 18:16:29
只是稍微阅读一下泛型。我已经写了一个小的测试工具…
public interface IAnimal
{
void Noise();
}
public class MagicHat<TAnimal> where TAnimal : IAnimal
{
public string GetNoise()
{
return TAnimal.//this is where it goes wrong...
}
}
但出于某种原因,即使我对类型进行了通用约束,它也不会让我返回TAnimal.Noise()…?
我错过什么了吗?你需要一个可以调用Noise()的对象
public string GetNoise( TAnimal animal )
{
animal.Noise()
...
}
我认为你可能需要在你的MagicHat类中添加一个TAnimal类型的对象
下面是c# Corner中的一个很好的例子:
public class EmployeeCollection<T> : IEnumerable<T>
{
List<T> empList = new List<T>();
public void AddEmployee(T e)
{
empList.Add(e);
}
public T GetEmployee(int index)
{
return empList[index];
}
//Compile time Error
public void PrintEmployeeData(int index)
{
Console.WriteLine(empList[index].EmployeeData);
}
//foreach support
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return empList.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return empList.GetEnumerator();
}
}
public class Employee
{
string FirstName;
string LastName;
int Age;
public Employee(){}
public Employee(string fName, string lName, int Age)
{
this.Age = Age;
this.FirstName = fName;
this.LastName = lName;
}
public string EmployeeData
{
get {return String.Format("{0} {1} is {2} years old", FirstName, LastName, Age); }
}
}