简体   繁体   English

C#泛型列表作为函数参数

[英]C# generic list as function parameter

I am retrieving a list from a table in database: 我正在从数据库中的表中检索列表:

var dependency = (from ctf in dc.Fields
                  join ctfd in dc.FieldsDependencies on ctf.id equals ctfd.Fieldid_depend
                  where ctf.ctid == ctid && ctf.fieldname == fieldname
                  select ctfd).ToList();

I am passing this list as parameter in another function: 我将此列表作为参数传递给另一个函数:

public void DoYesDeleteDepField<T>(string fieldname, List<T> dep)

How I can change it so I can retrieve the id field? 如何更改它以便可以检索id字段?

But I cant iterate through the list and get the depsingle.id field. 但是我无法遍历列表并获得depsingle.id字段。

foreach (var depsingle in dep)
        { var depsingleid = depsingle.id //ERROR
.....

您需要定义什么是T .. public void ...其中T:IHasId或在类级别定义它

It doesn't know that the <T> has the parameter .id so either cast it (like this var a = (int)something or var a = something as int ), or write it to something less generic from the List<t> . 它不知道<T>具有参数.id,所以要么将其强制转换(例如var a = (int)something or var a = something as int ),要么将其写入List<t> eg List<classname> . 例如List<classname>

As T can be anything from int to MyClass there´s no member called id on all those types. 由于T可以是从intMyClass 任何东西 ,因此在所有这些类型上都没有名为id成员。 Thus you need a generic constraint that tells the compiler what types are possible for T , eg: 因此,您需要一个通用约束来告诉编译器T可能的类型,例如:

public void DoYesDeleteDepField<T>(string fieldname, List<T> dep) where T: MyClass

or omit generics completely as only one type is possible making the term generic quite useless. 或完全省略泛型,因为只有一种类型是可能的,这使泛型一词毫无用处。 Simply define a class that hilds the values from your join and pass this to your method: 只需定义一个隐藏联接中值的类并将其传递给您的方法即可:

class MyClass
{
    public string Id { get; set; }
    // further properties
}

Now create instances of those objects from your query: 现在从查询中创建这些对象的实例:

var result = (from ctf in dc.Fields
              join ctfd in dc.FieldsDependencies on ctf.id equals ctfd.Fieldid_depend
              where ctf.ctid == ctid && ctf.fieldname == fieldname
              select new MyClass 
              { 
                  id = ctf.id,
                  // further properties
              }).ToList();

public void DoYesDeleteDepField(string fieldname, List<MyClass> dep)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM