为什么我的通用< T>没有解决? [英] Why does my generic <T> is not Resolved?
问题描述
我有一个电影类:
内部类Movie
{
public string Name {get ;组; }
public string Year {get;组; }
}
我有这样的代码:
var Movies = CreateMovies(); // IEnumerable的<电影和GT;
var sorter = new Sorter< Movie>();
sorter.AddSort(Movies,m => m.Year,a => a.Name,.....尽可能多的我想....);
以下是 Sorter
类:
class Sorter< T>
public void AddSort(IEnumerable< T> movs,params Expression< Func< T,object>> [] funcs)
{
/*...*/
movs.OrderBy(d => d。); //< -----这是问题:列在哪里?
问题:
当我在 d
上需要智能时,它会显示我:
I don不明白为什么 T
不会被推断为电影
:
<看看有多少地点推断 T
是电影
:
如何让这些电影字段显示,而不会更改为 Ienumerable< Movies>
? 在编译 Sorter
类时,编译器不会' t知道它将会是什么类型,所以它不能分辨将使用它的用户是否具有 Year
属性。
但是,您可以使用限制条件 :
class Sorter< T>其中T:电影
编译器知道给定的类 T
将有年属性以及其他属性
在泛型类型定义中,where子句用于指定
类型的约束,该类型可用作泛型声明中定义的类型
参数的参数。例如,您可以
声明一个泛型类MyGenericClass,使得类型参数
T实现IComparable接口:
< p>因为它表示你甚至不需要做
$ b $ pre> class Sorter< T> T:电影
我们可以满意
class Sorter< T> T:ImyInterface
和 ImyInterface
将包含属性名称
和年
。
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 :
I don't understand why T
is not inferred as Movie
:
Look how many locations are inferring that T
is a Movie
:
How can I make those Movie Fields to Appear , without changing to Ienumerable<Movies>
?
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
.
这篇关于为什么我的通用< T>没有解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!