简体   繁体   English

名单 <T> &哪里T:

[英]List<T> & where T :

I have simple code witch works ok: 我有简单的代码巫婆工作正常:

public class Example
{

    private List<SomeClass> _list = new List<SomeClass>();

    public void Add(SomeClass _b) {
        _list.Add(_b);
    }

}

it possible to add SomeClass to _list something like this? 有可能将SomeClass添加到_list这样的东西? (without specifying argument)? (没有指定参数)?

public void Add<T>() where T : SomeClass
{

}

Assuming that SomeClass has a default constructor, you can: 假设SomeClass有一个默认构造函数,你可以:

public void Add<T>() where T : SomeClass, new()
{
    _list.Add(new T());
}

If SomeClass does not have a default constructor then you won't be able to write new T() and you will need to find another way of getting a T object. 如果SomeClass没有默认构造函数,那么你将无法编写new T() ,你需要找到另一种获取T对象的方法。

You may use generics: 你可以使用泛型:

public class Example<T>
{
 private List<T> = _list = new List<T>();
 public void Add(T element)
 {
   _list.Add(element);
 }
}

What would you be adding? 你会加什么? I don't see any point to that. 我认为没有任何意义。 The external consumer of Example would not be able to add anything. Example的外部使用者将无法添加任何内容。

You would have to do 你必须这样做

public void Add<T>(T _b) where T : SomeClass
{

}

But it is pretty pointless and means the same thing as you existing code. 但它毫无意义,与现有代码的含义相同。

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

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