简体   繁体   English

如何禁用类型转换从接口到实现接口的类

[英]How to disable type casting from interface to class that implements interface

How do I disable casting from interface IFoo to class Bar? 如何禁用从接口IFoo到Bar类的转换? Is it even possible? 可能吗

Assembly one 组装一

public interface IFoo
{
   string Name { get; }
}

public class Foo : IFoo
{
   public int SecretValue { get; private set; }
   public string Name     { get; private set; }
}

Assembly two 大会二

public class Bar : Foo
{
   private IFoo secretFoo;
}

Can I prevent Bar from casting secretFoo to type Bar and thus accessing the value of SecretValue? 我可以阻止Bar强制将secretFoo转换为Bar类型,从而访问SecretValue的值吗?

Change Bar 's base class from Foo to IFoo , and property secretFoo from type IFoo to Foo . Bar的基类从Foo更改为IFoo ,并将属性secretFooIFoo类型更改为Foo

public class Bar : IFoo
{
    private Foo secretFoo;
    public string Name {
        get
        {
            return secretFoo.Name;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM