1

我正在使用 C#,我没有很多经验(到目前为止,我主要使用 java/php/javascript)

我想要的是一个类,我在其中保存了一些数据,这些数据只能由另一个类写入,但仍然可以由程序中的其他类读取。

像这样的东西:

public class DataObtainer{
 DataItem[] Items;
 public DataObtainer(){
  Items = new DataItem[20];
 }
 public void Update(){
  Items[0].SomeProperty = 5;//Being able to change SomeProperty
 }
 //Class only contains properties
 public class DataItem{
  public int SomeProperty;
 }
}

public class AnyOtherClass{
 public void SomeMethod(){
  DataObtainer do = new DataObtainer();
  //What I want:
  DataItem di  = do.items[0];
  Console.WriteLine(di.SomeProperty);//Being able to read SomeProperty
  di.SomeProperty = 5;//Not allow this, not being able to change SomeProperty
 }
}
4

3 回答 3

3

使用接口。

public interface IData
{
   string Data1 { get;}
   int MoreData { get;}
}

class Data : IData
{
   public string Data1 { get; set;}
   public int MoreData {get; set;}
}

public class DataObtainer
{
   private Data[] items;
   public DataObtainer()
   {
      items = new Data[20];
   }
   public IEnumerable<IData> Items
   {
      get
      {
         return items;
      }
   }

   public void Update()
   {
      Items[0].MoreData = 5;//Being able to change MoreData
   }
}

public class AnyOtherClass
{
   public void SomeMethod()
   {
       DataObtainer do = new DataObtainer();
       //What I want:
       IData di  = do.Items.First();
       Console.WriteLine(di.MoreData);//Being able to read SomeProperty
       di.SomeProperty = 5;//this won't compile
   }
}

解释:

  1. 创建一个要提供给代码的接口(IData)
  2. 在该接口的实现中创建
  3. 在获取器中存储实现
  4. 仅授予对接口的其他代码访问权限。这不会让他们访问更改值。
  5. 如果需要,调用代码可以强制转换为实现,但随后它们违反了合同并且所有赌注都被取消了。
于 2010-08-29T03:44:32.740 回答
0

您应该创建DataItem一个外部(非嵌套)abstract类,然后创建一个内部(私有)类来继承它并提供公共 mutator 方法。

DataObtainer中,您可以将对象强制转换为私有继承类并修改它们。

于 2010-08-29T03:26:47.927 回答
0

这种设计对我来说似乎很尴尬。您可以控制代码,因此除非您正在设计某种框架/api,否则您要求做的并不是真正必要的。如果一个类不应该能够修改属性,请不要修改该属性或不提供 setter。

也许您可以多解释一下您需要什么或为什么要完成此操作,以帮助我们了解为您提供实现目标的最佳方法。

使用基本继承的简单示例

// Class used to read and write your data
public class DataBuilder : Data {
    public void SetValue(int value) {
        base.m_SomeValue = value; // Has access to protected member
    }
}

// Class used to store your data (READONLY)
public class Data {
    protected int m_SomeValue; // Is accessible to deriving class
    public int SomeValue {     // READONLY property to other classes
                               // EXCEPT deriving classes
        get {
            return m_SomeValue;
        }
    }
}

public class AnyOtherClass {
    public void Foo() {
        DataBuilder reader = new DataBuilder();
        Console.WriteLine(reader.SomeValue); // *CAN* read the value
        reader.SomeValue = 100; // CANNOT *write* the value
    }
}
于 2010-08-29T03:47:53.310 回答