Domanda

I'm receiving the following compile-time issue with this extension method.

error CS1061: 'SomeClass' does not contain a definition for 'SomeProperty' and
    no extension method 'SomeProperty' accepting a first argument of type 'SomeClass' could be found (are
    you missing a using directive or an assembly reference?)

The classes are all within the same project and it appears I can declare the class without issue. How do I resolve this?

using System;
using System.Collections;
using System.Collections.Generic;

public static class SomeClassListEx 
{
    public static List<SomeClass> SomeMethod<SomeClass>(this IEnumerable<SomeClass> list, int id) // where T : SomeClass
    {       
        List<SomeClass> result = new List<SomeClass> ();

        foreach (SomeClass something in list)
        {
            if(something.SomeProperty.SomeList.Contains(id))
            {
                result.Add (something);
            }
        }

        return result;
    }

}

public abstract class SomeClass : IEquatable<SomeClass>
{
    public SomethingElse SomeProperty { get; set; }

}

public interface SomethingElse
{
    List<int> SomeList { get; }
}
È stato utile?

Soluzione

You made your method generic, so after SomeMethod<SomeClass> SomeClass is no longer your class, it's a generic parameter, which can be replaced by anything when you actually call the method.

Your extension method shouldn't be generic:

public static List<SomeClass> SomeMethod(this IEnumerable<SomeClass> list, int id)
{       
    List<SomeClass> result = new List<SomeClass> ();

    foreach (SomeClass something in list)
    {
        if(something.SomeProperty.SomeList.Contains(id))
        {
            result.Add (something);
        }
    }

    return result;
}

Altri suggerimenti

In addition to @MarcinJuraszek's answer, I would say if you want to make it generic for your various subclasses that will derive from the abstract class SomeClass, you can do this:

Note I use the generic parameter T here, and add the generic constraint where T : SomeClass which you had commented out in your code. It was confusing because you were using the same name of a class as your generic paramter name; this wouldn't be allowed.

public static List<T> SomeMethod<T>(this IEnumerable<T> list, int id)  where T : SomeClass
{
    List<T> result = new List<T>();

    foreach (T something in list)
    {
        if (something.SomeProperty.SomeList.Contains(id))
        {
            result.Add(something);
        }
    }

    return result;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top