Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

c# - Why does my generic <T> is not Resolved?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...