2011-12-01 151 views
0

只是对泛型进行一些阅读。我已经写了一个小的测试工具...为什么智能感知不能在我的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()...?

我错过了什么吗?

+0

IAnimal是一个接口,你需要定义噪声法。 – JonH

回答

8

您需要一个可以调用Noise()的对象。

public string GetNoise(TAnimal animal) 
{ 
    animal.Noise() 
    ... 
} 
+1

+1击败我15秒:)也许我会添加一些额外的答案:你正试图调用一个类型的实例方法。 – leppie

+0

+1打我时,我也打字。 – NexAddo

0

我觉得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); } 
    } 
}