简体   繁体   中英

Why doesn't intellisense work on my Generic?

Just doing a bit of reading up on Generics. I have written a little test harness...

public interface IAnimal
    {
        void Noise();
    }

    public class MagicHat<TAnimal> where TAnimal : IAnimal
    {
        public string GetNoise()
        {
            return TAnimal.//this is where it goes wrong...
        }
    }

But for some reason even though I have put a generic constraint on the Type it wont let me return TAnimal.Noise()...?

Have I missed something?

You need an object on which you can call Noise().

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

I think you might need an object of the type TAnimal in your class MagicHat

Here is a nice example from 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); }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM