【问题标题】:Get/Set Method for Array Properties数组属性的获取/设置方法
【发布时间】:2013-06-26 12:28:46
【问题描述】:

我有一个Entry 类,我想通过它向 WPF 中的 Gridview 公开数据(通过 List<Entry>)。我需要在 Gridview 中为 Entry 对象的每个属性设置一列(还为 propsA3 的每个条目获取一列),但我不确定如何为数组定义 getter/setter 方法以便始终获取/设置基础数据的属性。

public Entry
{
  private ObjA oA;
  private ObjB[] listB;

  public int PropA1 {get {return oA.Prop1;} set {oA.Prop1 = value;}}
  public int PropA2 {get {return oA.Prop2;} set {oA.Prop1 = value;}}
  public int[] propsA3;
}

public ObjA
{
   public int Prop1 {get, set};
   public int Prop2 {get, set};

   public int getVal3(ObjB b) {return calSomethin(b);}
   public int setVal3(ref ObjB b, int val) { /*do something to ObjB*/}
}

public ObjB
{
   Byte[] data;
}

我想要的 PropsA3 具有以下获取/设置行为:

Entry e;

得到: int a = e.propsA3[i]; => a = oA.getVal3(listB[i]);

设置: e.propsA3[i] = 5; => oA.setVal3(listB[i], val);

这可能吗?如何实现这一点,或者我必须如何更改类设计才能获得预期的结果?

【问题讨论】:

    标签: c#


    【解决方案1】:

    这是可能的,但我不确定有什么好处,你可以使用包装类来做到这一点。例如:

    public class Entry
    {
        private ObjA oA;
        private ObjB[] listB;
    
        public int PropA1 {get {return {oA.Prop1}} set {oA.Prop1 = value;}}
        public int PropA2 {get {return {oA.Prop2}} set {oA.Prop1 = value;}}
        public EntryProperties propsA3;
    
        public Entry() 
        {
            propsA3 = new EntryProperties(this);
        }
    
        public class EntryProperties 
        {
            private Entry _entry;
    
            public EntryProperties(Entry entry) {
                _entry = entry;
            }
    
            public int this[int index] {
                get { return _entry.oA.getVal3(_entry.listB[index]); }
                set { _entry.oA.setVal3(_entry.listB[index], value); }
            }
        }
    }
    

    话虽如此,我真的认为这不是一个好主意 - 为什么不在网格中定义一个具有所需属性的视图模型类,然后手动设置这些属性,或者使用 AutoMapper 或 ValueInjector 之类的东西来这样做...

    【讨论】:

    • 感谢您的回答。我没有设置必须访问e.propsA3[i],但我认为我的视图模型将显示List<Entry,因此我认为我需要能够获取/设置所有这些propsA3才能设置它们来自 DataGrid。我仍然是 WPF 和 MVVM 设计模式的初学者。也许我会发布添加我的问题/发布一个新问题以反映我正在努力实现的整个任务。但我也会研究 ValueInjector。
    • 如果您知道属性是什么,那么我建议您明确添加它们,或者如果这不是您真正想要的,也许可以考虑使用 DataTable 或其他 Dictionary 等效项
    【解决方案2】:

    这应该可以工作

    pulbic Entry 
    {
        public ObjA propsA3 { get; set; }
    }
    
    public ObjA
    {
       public int Prop1 {get, set};
       public int Prop2 {get, set};
    
       public int this[ObjB b]
       {
          get { return getVal(b); }
          set { /* do something*/ }
       }
    
       private int getVal3(ObjB b) {return calSomethin(b);}
       private int setVal3(ref ObjB b, int val) { /*do something to ObjB*/}
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多