Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a class Movie :

internal class Movie
    {
        public string Name { get; set; }
        public string Year { get; set; }
    }

And I have this code :

 var Movies = CreateMovies(); //IEnumerable<Movie>
 var sorter = new Sorter<Movie>();
 sorter.AddSort(Movies,  m => m.Year , a=>a.Name ,.....as many as I want....);

And here is the Sorter class :

 class Sorter<T>
{
    public void AddSort(IEnumerable<T> movs,  params Expression<Func<T, object>>[]    funcs)
    {
                 /*...*/ 
        movs.OrderBy(d=>d.); //<----- here is the problem : where is the columns ?
    }
}

Question :

When I need intellisence on the d , it shows me :

enter image description here

I don't understand why T is not inferred as Movie :

Look how many locations are inferring that T is a Movie :

enter image description here

How can I make those Movie Fields to Appear , without changing to Ienumerable<Movies> ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
184 views
Welcome To Ask or Share your Answers For Others

1 Answer

at the time of compiling Sorter class, the compiler doesn't know what type it's going to be, so it can't tell if the user that will use it will have an Year property or not.

however, you can use where constrains:

class Sorter<T> where T: Movie

that way the compiler knows that the given class of T will have Year property as well as other properties

In a generic type definition, the where clause is used to specify constraints on the types that can be used as arguments for a type parameter defined in a generic declaration. For example, you can declare a generic class, MyGenericClass, such that the type parameter T implements the IComparable interface:

so as it says you don't even have to do

class Sorter<T> where T: Movie

we can just be satisfied with

class Sorter<T> where T: ImyInterface

and ImyInterface will contain properties of Name and Year.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...