[英]Why doesn't intellisense work on my Generic?
只是做一些泛型的阅读。 我写了一些测试工具...
public interface IAnimal
{
void Noise();
}
public class MagicHat<TAnimal> where TAnimal : IAnimal
{
public string GetNoise()
{
return TAnimal.//this is where it goes wrong...
}
}
但是由于某种原因,即使我对Type设置了通用约束,它也不允许我返回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); }
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.