C# 使用显式接口实现
我正在尝试使用显式接口实现更改接口实现类中的属性类型C# 使用显式接口实现,c#,interface,C#,Interface,我正在尝试使用显式接口实现更改接口实现类中的属性类型 interface ISample { object Value { get; set; } } class SampleA : ISample { SomeClass1 Value { get; set; } object ISample.Value { get { return this.Value; } set { this.Value
interface ISample
{
object Value { get; set; }
}
class SampleA : ISample
{
SomeClass1 Value { get; set; }
object ISample.Value
{
get { return this.Value; }
set { this.Value = (SomeClass1)value; }
}
}
class SampleB : ISample
{
SomeClass2 Value { get; set; }
object ISample.Value
{
get { return this.Value; }
set { this.Value = (SomeClass2)value; }
}
}
class SomeClass1
{
string s1;
string s2;
}
但是当我需要在函数中传入接口obj时,我无法访问SomeClass1或SomeClass2的对象
例如:
public void MethodA(ISample sample)
{
string str = sample.Value.s1;//doesnt work.How can I access s1 using ISample??
}
我不知道这是否可以理解,但我似乎找不到更简单的方法来解释这一点。有没有办法使用接口ISample访问SomeClass1的属性
感谢这是因为您收到了作为接口的对象,所以它不知道类的新属性类型。您需要:
public void MethodA(ISample sample)
{
if (sample is SampleA)
{
string str = ((SampleA)sample).Value.s1;
}
}
更好的解决方案可能是使用该模式,该模式将有用于处理不同ISample的实现。第二个示例不起作用,因为
SomeClass1
是属性的类型,而不是ISample
的类型,如果ISample
是samples
则第一个示例将抛出异常使用约束:)我假设事物是公共的,他的代码显示它不是公共的。我为ntziolis添加了一些类型检查-我没有显示安全路径,我只是显示如何强制转换对象。显然,应该添加一些设计来使代码更可靠。@user1299340-我的答案被接受了吗?!?![总是追求更多的SO分数]