为什么智能感知不能在我的Generic上工作?
问题描述:
只是对泛型进行一些阅读。我已经写了一个小的测试工具...为什么智能感知不能在我的Generic上工作?
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()...?
我错过了什么吗?
答
我觉得MagicHat
这里是C# Corner一个很好的例子,你可能需要的类型TAnimal的对象类:
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); }
}
}
IAnimal是一个接口,你需要定义噪声法。 – JonH