代码之家  ›  专栏  ›  技术社区  ›  Jon

C#从get返回一个只读变量;集合;

  •  36
  • Jon  · 技术社区  · 16 年前

    谢谢

    7 回复  |  直到 16 年前
        1
  •  52
  •   Jon Skeet    16 年前

    不,这是不可能的。例如,如果你返回一个 List<string> (而且它不是不可变的)然后调用者 能够添加条目。

    ReadOnlyCollection<T> .

    IEnumerable<T> 而不是 List<T>

        2
  •  6
  •   Anton Gogolev    16 年前

    返回对精简界面的引用:

     interface IFoo
       string Bar { get; }
    
     class ClassWithGet
       public IFoo GetFoo(...);
    
        3
  •  3
  •   Jamie Ide    16 年前

    如果对象不是太复杂/太广泛,那么就围绕它编写一个包装器。

    例如:

    class A {
        public string strField = 'string';
        public int intField = 10;
    }
    
    class AWrapper {
        private A _aObj;
    
        public AWrapper(A aobj) {
          _aObj = A;
        }
    
        public string strField {
             get {
                return _aObj.strField;
             }
        }
    
        public int intField {
             get {
                return _aObj.intField;
             }
        }
    }
    

    如果你的基类不是一成不变的,这可能会变得有点复杂,而且可能无法很好地扩展,但对于大多数简单的情况,它可能会奏效。我认为这被称为立面模式(但不要引用我的话=)

        4
  •  3
  •   justlost    16 年前

    这是不可能的。获取并设置引用类型的访问器获取并设置对象的引用。您可以通过使用私有(或内部)setter来阻止对引用的更改,但如果对象被getter公开,则无法阻止对对象本身的更改。

        5
  •  2
  •   Matt Miguel Pragier    10 年前

    你的问题读起来像是在寻找:

    public PropertyName { get; private set; }
    

    但是,鉴于到目前为止的答案,我不确定我是否正确地解释了你的问题。此外,我凭什么质疑乔恩·斯基特? :)

        6
  •  0
  •   pingsft    13 年前

    我同意ReadOnlyCollection

     private List<Device> _devices;
    public readonly System.Collections.ObjectModel.ReadOnlyCollection<Device> Devices 
    {
     get
     { 
    return (_devices.AsReadOnly());
     } 
    

        7
  •  0
  •   cdie    9 年前

    我以某种方式面对过这个问题。 我有一个CategoryViewModel类,它有一个我想要私有只读的属性Category:

    public CategoryViewModel
    {
        private Category { get; }
    
    }
    

    public void ApplyAction(ICategoryRepository repo, Action<ICategoryRepository, Category> action)
    {
        action(repo, Category);
    }
    

     categoryViewModel.ApplyAction(_repository, (r, c) => r.MarkForInsertOrUpdate(c));
    

    推荐文章