假设我有一个带有只读属性的接口和一个具体类,其中该属性在构造函数中实例化并标记为只读。
internal interface IExample
{
ObservableCollection<string> Items { get; }
}
internal class Example : IExample
{
private readonly ObservableCollection<string> _items;
public Example()
{
_items = new ObservableCollection<string>();
}
public ObservableCollection<string> Items
{
get { return _items; }
}
}
当我使用接口时,Resharper 警告我在调用代码时可能有一个空引用。
public class ExampleWithWarnings
{
public void Show()
{
IExample example = new Example();
// resharper warns about null reference
example.Items.Add( "test" );
}
}
我意识到根据定义,接口并不能保证该属性将具有值。(我也认识到接口上的属性并不理想)。但我知道这个属性总是有价值的。
我可以在界面上放置任何可以防止 Resharper 显示警告的魔法属性吗?我宁愿不必用禁用编译指示警告来装饰类的所有用法。