سؤال

I have two classes GenericNameValue and SpecificNameValue with inherits from GenericNameValue.

I have a function that takes the parameter List<GenericNameValue>. I would like to be able to pass in List<SpecificNameValue>. The function does nothing with the special properties of the SpecificNameValue.

What is the best method to do this?

public class GenericNameValue
{
    public string FieldName{get;set;}
    public string FieldValue{get;set;}
}

public class SpecificNameValue : GenericNameValue
{
    public string SpecificFieldValue{ get; set; }
}

public static UtitlityClass
{
    public string CombineAllFields(List<GenericNameValue> mylist)
    {
        //.... do stuff with each item
    }
}

//......Example of calling the utilityclass
string stuff = UtilityClass.CombineAllFields(mySpecificNameValue);

So is there a specific syntax I am missing? Should I be using something different like Abstracts?

Sorry this is just one of those things that has caused me headaches for a while and would like an elegant solution.

هل كانت مفيدة؟

المحلول

List<T> is not covariant, your method will work with just an IEnumerable<> :

  public string CombineAllFields(IEnumerable<GenericNameValue> mylist)
  {
      .... do stuff with each item
  }

The full definitions from the library:

public class List<T> : IList<T> { }
public interface IList<T> : IEnumerable<T> { }
public interface IEnumerable<out T> { }

Note that your down-cast can only work with an interface that uses that out modifier.

Consider that using either a List<T> or an IList<T> parameter would allow your method to change the List. Deletions wouldn't matter but we have to prevent adding a GenericNameValue to a List<SpecificNameValue>. IEnumerable<> won't let you add to a collection so covariance is safe.

نصائح أخرى

Henk Holterman's answer is definitely the way to go.

If you're set on using a List<T> or you're in .NET 2.0 or 3.0, you have the option of using a generic parameter with a constraint:

public static string CombineAllFields<T>(List<T> mylist) where T : GenericNameValue
{
    //.... do stuff with each item
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top