有没有更优雅的方法来确保构造函数始终被调用至少一个值,而不是我在这里得到的值?我这样做了,因为如果没有提供值,我想要编译器错误.
public class MyClass
{
private readonly List<string> _things = new List<string>();
public string[] Things { get { return _things.ToArray(); } }
public MyClass(string thing, params string[] things)
{
_things.Add(thing);
_things.AddRange(things);
}
}
Run Code Online (Sandbox Code Playgroud)
编辑
根据评论,我已将代码更改为此...
public class Hypermedia : Attribute
{
private readonly Rel[] _relations;
public IEnumerable<Rel> Relations { get { return _relations; } }
public Hypermedia(Rel relation, params Rel[] relations)
{
var list = new List<Rel> {relation};
list.AddRange(relations);
_relations = list.ToArray();
}
}
Run Code Online (Sandbox Code Playgroud)
在尝试隐藏我想要做的事情之前编辑代码的道歉.从我的代码编辑器直接粘贴更容易!
Art*_*lev 13
代码合约怎么样?
public MyClass(params string[] things)
{
Contract.Requires(things != null && things.Any());
_things.AddRange(things);
}
Run Code Online (Sandbox Code Playgroud)
代码契约包括用于标记代码的类,用于编译时分析的静态分析器以及运行时分析器.
至少你会收到静态分析仪的警告.您可以在发布模式下关闭运行时分析以避免性能损失.
| 归档时间: |
|
| 查看次数: |
2810 次 |
| 最近记录: |