什么时候在这种情况下实例化对象?

Elu*_*FTW 0 c# design-patterns

我曾多次对这种形式的烦恼感到磕磕绊绊,所以我的问题是:代码场景的最佳模式/实践如下所示?

这是我最近写的方法体的一个例子:

public HashSet<char> SomeCharacters(IEnumerable<string> _hashes){

    HashSet<char> Result = new HashSet<char>();
    bool _firstpass = true;

    foreach (string _hash in _hashes) {
        if (_firstpass) {
            Result = new HashSet<char>(_hash);
            _firstpass = false;
        }
        else {
            // ...
            // some code that uses Result
        }
    }
    return Result;
}
Run Code Online (Sandbox Code Playgroud)

这很好,但令我讨厌的是第一行

HashSet<char> Result = new HashSet<char>();

我本能地喜欢替换它HashSet<char> Result;.编译器不会让我,因为else块使用Result它不识别为instanciated,虽然我知道它将在else块执行时.

上面的方法迫使我创建Result两次,这不是很好的原因(性能,代码美学,......).

请将此问题视为有关此类情况的问题,而不仅仅是针对此特定示例.谢谢!

Mar*_*age 5

只需null最初分配给变量:

HashSet<char> Result = null;
Run Code Online (Sandbox Code Playgroud)

然后你也可以摆脱_firstpass变量:

HashSet<char> Result = null;
foreach (string _hash in _hashes) {
    if (Result == null) {
        Result = new HashSet<char>(_hash);
    }
    else {
        // ...
        // some code that uses Result
    }
}
Run Code Online (Sandbox Code Playgroud)

如果迭代字符串集合的唯一目的是将字符串的所有字符放在a中,HashSet<char>那么你可以这样做:

var Result = new HashSet<char>(_hashes.SelectMany(s => s));
Run Code Online (Sandbox Code Playgroud)

这里的原则是,有时您可以使用"first pass create and add"逻辑将循环重写为更简单的LINQ语句,在这些语句中构建序列,然后使用ToList或在本例中使用HashSet构造函数创建最终对象.