代码之家  ›  专栏  ›  技术社区  ›  Justin Alexander

C中的“catchall”属性?

  •  1
  • Justin Alexander  · 技术社区  · 15 年前

    是否可以在C中创建“catchall”getter属性?

    class xyzFactory {
    
       public static object this.*(string name){
           get { return new name();}
      }
    }
    

    在PHP中,您可以编写如下内容

    //static getters are new to 5.3, so I didn't put it here.
    
    class xyzFactory{
        public _get($name){ return $name();}
    }
    
    6 回复  |  直到 6 年前
        1
  •  3
  •   Patrick Ali sasoli    6 年前

    你可以用类似黑客的方法来达到这个目的

    xyzFactory.Instance.Name
    

    其中静态实例属性的类型为 dynamic

    并使您从dynamicObject类派生XyzFactory。

    public xyzFactory : DynamicObject
    {
        private static xyzFactory _instance = new xyzFactory();
    
        private xyzFactory() { }
    
        public static dynamic Instance
        {
            get{ return _instance; }
        }
    
        public override bool TryGetMember(GetMemberBinder binder, out object result) {
            // ...
        }
    }
    
        2
  •  8
  •   Yann Schwartz    15 年前

    不在C 3中。在C 4.0中,您可以使用expando属性和 dynamic 关键字。

        3
  •  3
  •   Mehrdad Afshari    15 年前

    不,你不能用C来做。C是一种编译语言,在编译时静态地解析方法槽。它不支持将属性名作为字符串或类似的东西传递。

        4
  •  1
  •   Sergej Andrejev    15 年前

    最接近的是重载索引运算符([])。至少在C 4.0失效之前

        5
  •  0
  •   jk.    15 年前

    你可以用 property pattern 要实现这一点,正如其他人所说,C目前不会帮助您实现它。

        6
  •  0
  •   Maslow    15 年前

    你可以用 LinFu .它使用动态代理来允许 Duck Typing and Late Binding , Ruby-style Mixins