类级匿名类型?

时间:2010-09-23 08:08:33

标签: c#

是否可能创建一个类级别的匿名类型?像,

class MyClass {
    readonly var _myAnon = new { Prop = "Hello" };
}

我正在寻找一种简单的方法来创建类似字典的常量结构。


想要创建这样的东西,但有更多的类型安全性:

    readonly Dictionary<string, dynamic> _selectors = new Dictionary<string, dynamic>
    {
        { "order", new string[] {"ID","NAME","TAG"} },
        { "match", new Dictionary<string, Regex> {
            { "ID", new Regex(@"#((?:[\w\u00c0-\uFFFF-]|\\.)+)") },
            { "CLASS", new Regex(@"\.((?:[\w\u00c0-\uFFFF-]|\\.)+)") },
            { "NAME", new Regex(@"\[name=['""]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['""]*\]") },
            { "ATTR", new Regex(@"\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['""]*)(.*?)\3|)\s*\]") },
            { "TAG", new Regex(@"^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)") },
            { "CHILD", new Regex(@":(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?") },
            { "POS", new Regex(@":(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)") },
            { "PSEUDO", new Regex(@":((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['""]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?") } }
        },
        { "leftMatch", new object() },
        { "attrMap", new Dictionary<string, string> {
            { "class", "className" },
            { "for", "htmlFor" } }
        }
    };

1 个答案:

答案 0 :(得分:2)

您可以随时声明自己的类型。它不需要是匿名的:

class MyClass
{
    readonly MarkProperties _mark = new MarkProperties();
    public class MarkProperties
    {
        public string Name = "Mark";
        public int Age = 22;
        public DateTime Birthdate = new DateTime(...);
    }
}

因此,您在编辑后的问题版本中提供的代码将类似于:

readonly Selectors _selectors = new Selectors();
public class Selectors
{
    public string[] Order = { "ID", "NAME", "TAG" };
    public Match Match = new Match();
    public class Match
    {
        public Regex ID = new Regex(@"#((?:[\w\u00c0-\uFFFF-]|\\.)+)");
        public Regex CLASS = new Regex(@"\.((?:[\w\u00c0-\uFFFF-]|\\.)+)");
        public Regex NAME = new Regex(@"\[name=['""]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['""]*\]");
        public Regex ATTR = new Regex(@"\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['""]*)(.*?)\3|)\s*\]");
        public Regex TAG = new Regex(@"^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)");
        public Regex CHILD = new Regex(@":(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?");
        public Regex POS = new Regex(@":(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)");
        public Regex PSEUDO = new Regex(@":((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['""]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?");
    }
    public object LeftMatch = new object();
    public AttrMap AttrMap = new AttrMap();
    public class AttrMap
    {
        public string Class = "className";
        public string For = "htmlFor";
    }
}