简体   繁体   中英

Use <T> in class properties declare in C#

I have a class like this

public class Tbl
{
    public string Name {get; set}
    public anyClass Datasource {get; set;} //I don't know what to use there
}

//Usage:
List<anyClass> anyList = GetList(); // Assuming I had a list
Tbl Table = new Tbl();
Table.Name = "Table1";
Table.Datasource = anyList;

Here, my propblem is making the Datasource can accept any input Class. How can I declare the Datasource for Tbl class right way?

Thanks very much

If it was Tbl<T> , you might choose to expose IList<T> as the DataSource :

public class Table<T>
{
    public string Name {get; set}
    public IList<T> DataSource {get; set;}
}

For non-generic data you might choose to use the non-generic IList ; however, in the core framework it is fairly routine to use object as a DataSource , as this allows use of both IList and IListSource (an abstraction around obtaining a list).

You use the type Object :

public object Datasource { get; set; }

If you want to use generics to specify the type:

public class Tbl<T> {
  public string Name { get; set }
  public T Datasource { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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