类属性在程序集或命名空间外部为只读



我有一个类的对象,我想通过接口传递给另一个程序集。

因为我传递的是一个引用,所以所有暴露的属性、方法等都可以从创建它的程序集外部修改。

是否有一种方法,我可以访问它的程序集(或名称空间)内的所有暴露的元素,并在其他程序集(或名称空间)的元素是只读的?

作为一种解决方法,在写入当前范围内应该是只读的元素时,只使用断言也是可以的。

认为您需要 internal 访问修饰符。它限制了对当前程序集的可访问性。

假设我们想要构建一个Person类:

public class Person
{
   public string Name { get; set; }
   internal int Bio { get; set; }
   private int age;
   public int Age
   {
       get { return age; }
       internal set { age = value; }
   }
   public string Location { get; internal set; }
}
  • Namepublic,因此对所有组件可见。

  • Biointernal,因此对当前程序集只有可见。

  • Age有一个隐式 public的setter,因为成员是public。setter s 显式 internal。这意味着所有程序集都可以获得该值,但只有当前程序集可以设置该值。

  • Location与上面相同,但是一个自动属性。

你可以在这里阅读更多关于访问修饰符的信息。

(有一个例外,那就是InternalsVisibleTo属性)

你在找这样的东西吗?

  public class Sample {
    private int m_Data;
    // property (and "get") is public - anyone can read the property
    public int Data {
      get { // "get" has "public" modifier as property does
        return m_Data; 
      }
      internal set { // "set" is internal - caller should be in the same assembly 
        m_Data = value;
      }
    }
  }

因此,在程序集内Dataread/write属性而readonly当它在程序集外被调用时

您可以创建具有只读属性的接口,您可以使用显式接口实现internal关键字来限制对其他程序集的某些成员的访问。

在这个简单的示例中说明了所有三种方法:

public interface IMyClass
{
    // has only getter and is read-only
    int MyProperty { get;  }
    string MyMethod();
}
class MyClass : IMyClass
{        
    // setter can be accessed only from current assembly
    public int MyProperty { get; internal set; }
    // this method can by invoked from interface (explicit implementation)
    string IMyClass.MyMethod()
    {
        return "logic for your interface to use outside the assembly";        
    }
    // this method can by invoked from current assembly only
    internal string MyMethod()
    {
        return "logic inside the assembly";
    }
}
class Program
{
    static void Main()
    {
        MyClass instance = new MyClass();
        instance.MyProperty = 10;
        // (instance as IMyClass).MyProperty = 20;        property cannot be assigned it's read-only
        Console.WriteLine((instance as IMyClass).MyProperty);
        Console.WriteLine((instance as IMyClass).MyMethod());
        Console.WriteLine(instance.MyMethod());
    }       
}    
输出:

10
logic for your interface to use outside the assembly
logic inside the assembly

最新更新