避免外部代码中的属性不明确
本文关键字:属性 不明确 代码 外部 | 更新日期: 2023-09-27 18:00:56
我正在使用一个外部库(无法更改(,并且在尝试设置属性时看到一个不明确的引用。
这是一个示例(不是实际的库或属性名称(
外部代码:
namespace ExternalLibrary1.Area1
{
public interface Interface0: Interface1, Interface2
{
}
public interface Interface1
{
double Item { get; set; }
}
public interface Interface2
{
double Item { get; set; }
}
public class Class0 : Interface0
{
double Item;
}
}
我的代码:
Interface0 myObject = new Class1();
myObject.Item = 2.0;
//above line gives me compile error "Ambiguity between 'ExternalLibrary1.Area1.Interface1.Item' and 'ExternalLibrary1.Area1.Interface2.Item'
正如在我的代码中看到的,我在尝试分配给Item
属性时遇到了一个模糊性错误。
我不能改变这个图书馆。我知道我想将值分配给Interface1
。有没有什么方法可以明确指定它来防止编译错误?
对于设计Interface0
、Interface1
、Interface2
类型层次结构的人来说,这似乎是一个奇怪的决定。您可以做的是将要设置属性的接口类型强制转换为(或分配给的引用(:
Interface1 myObject = new Class1();
myObject.Item = 2.0;
除了Asad的答案外,如果需要在Interface0
上使用其他属性和方法,您也可以在赋值时强制转换它。
Interface0 myObject = new Class1();
(myObject as Interface1).Item = 2.0;