C# 为什么';intellisense不能在我的通用计算机上工作吗?
只是做一些泛型的阅读。我已经写了一个小测试工具C# 为什么';intellisense不能在我的通用计算机上工作吗?,c#,generics,C#,Generics,只是做一些泛型的阅读。我已经写了一个小测试工具 public interface IAnimal { void Noise(); } public class MagicHat<TAnimal> where TAnimal : IAnimal { public string GetNoise() { return TAnimal.//this is where it goes w
public interface IAnimal
{
void Noise();
}
public class MagicHat<TAnimal> where TAnimal : IAnimal
{
public string GetNoise()
{
return TAnimal.//this is where it goes wrong...
}
}
公共接口IAnimal
{
空洞噪声();
}
公共类MagicHat,其中TAnimal:IAnimal
{
公共字符串GetNoise()
{
返回塔尼马尔//这就是出错的地方。。。
}
}
但是出于某种原因,即使我对类型设置了泛型约束,它也不允许我返回TAnimal.Noise()
我遗漏了什么吗?您需要一个可以调用Noise()的对象
我认为您可能需要在类MagicHat中使用TAnimal类型的对象 以下是一个很好的例子:
公共类EmployeeCollection:IEnumerable
{
List empList=新列表();
公共无效雇主(TE)
{
添加(e);
}
公共T GetEmployee(整数索引)
{
返回雇主[索引];
}
//编译时错误
public void PrintEmployeeData(int索引)
{
Console.WriteLine(雇员列表[index].EmployeeData);
}
//foreach支持
IEnumerator IEnumerable.GetEnumerator()
{
返回empList.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
返回empList.GetEnumerator();
}
}
公营雇员
{
字符串名;
字符串LastName;
智力年龄;
公共雇员(){}
公共雇员(字符串fName、字符串lName、整数年龄)
{
这个。年龄=年龄;
this.FirstName=fName;
this.LastName=lName;
}
公共字符串EmployeeData
{
获取{return String.Format(“{0}{1}是{2}岁”,FirstName,LastName,Age);}
}
}
IAnimal是一个接口,您需要定义noise方法。+1比我快15秒:)也许我会在回答中添加一些额外内容:您正在尝试调用类型的实例方法。
public string GetNoise( TAnimal animal )
{
animal.Noise()
...
}
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); }
}
}