2

我已经创建了一个类(显示其中一个),其中包含我想要迭代的 const 字符串。

public static class HTDB_Cols
{
    public sealed class Assistant
    {
        public const string EntryID  = "entryID",
                CustName  = "custName",
                SerialNum  = "serialNum",
                UserName  = "userName",
                Password  = "password",
                EndDate  = "end_date",
                CustID  = "custID",
                TmpCheck  = "tmpCheck",
                Isfamily  = "isfamily",
                Isserver  = "isserver";
    }
}               

public static class DB
{    
    public static void insert(string TableName)
    {
        ColumnsCollection = typeof(HTDB_Cols).GetNestedTypes().Where(f => f.DeclaringType.Name.ToLower().Equals(TableName.ToLower()));
    } 
}

上面的代码显示了我的尝试,但即使经过大量试验和错误,我仍然无法正确完成。

我希望将所有列的列表作为 const 集合数组或列表。

4

2 回答 2

5
var dict = typeof(HTDB_Cols).GetNestedTypes()
            .First(t=>String.Compare(t.Name,TableName,true)==0)
            .GetFields()
            .ToDictionary(f => f.Name, f => f.GetValue(null));

获取列表

var list = typeof(HTDB_Cols).GetNestedTypes()
            .First(t => String.Compare(t.Name, TableName, true) == 0)
            .GetFields()
            .Select(f => f.GetValue(null) as string)
            .ToList();
于 2012-11-01T17:27:53.423 回答
1

看起来您需要的是enum

enum Assistant
{
    EntryID,
    CustName,
    SerialNum,
    UserName,
    Password,
    EndDate,
    CustID,
    TmpCheck,
    Isfamily,
    Isserver
};

然后,您可以通过执行以下操作将所有这些名称作为字符串:

string[] allNames = Enum.GetNames(typeof(Assistant));

只要您可以接受让变量的名称成为您关心的实际值,这是一个有效的选择。我注意到它们在您的示例中并不完全相同,但主要是外壳。如果您可以处理使用变量名作为值,或者将变量名更改为您需要的值,那么这可能是您的最佳选择。

现在,如果变量名称与它们所代表的值不同确实很重要,或者如果您需要表示非法标识符的值(例如,您的值之一有空格,那就不好了,他们可以永远不要以数字开头,否则它们可能太长而不能成为方便的名称)。如果是这种情况,那么您真正想要的是一个由字符串支持的枚举,而不是整数或其他数字类型。这在 C# 中是不可能的,但是因为这在我实际编写以下类之前就​​已经出现了,这是我创建自己的字符串支持的枚举的最佳尝试。如果您确实需要与它们所代表的字符串值不同的变量名称,这应该适合您。

所有重要的东西都在顶部,后面的大部分内容Equals都只是语法糖。

public struct StringEnum
{
    #region Code that is to be configured
    //For each value to be publicly exposed add a new field.
    public static readonly StringEnum Alpha = new StringEnum("Alpha Value");
    public static readonly StringEnum Beta = new StringEnum("Beta Value");
    public static readonly StringEnum Invalid = new StringEnum("Invalid");


    public static IEnumerable<StringEnum> AllValues
    {
        get
        {
            yield return Alpha;
            yield return Beta;
            yield return Invalid;
            //...
            //add a yield return for all instances here.

            //TODO refactor to use reflection so it doesn't need to be manually updated.
        }
    }

    #endregion
    private string value;

    /// <summary>
    /// default constructor
    /// </summary>
    //private Group()
    //{
    //    //You can make this default value whatever you want.  null is another option I considered 
    //    //(if this is a class an not a struct), but you 
    //    //shouldn't have this be anything that doesn't exist as one of the options defined at the top of 
    //    //the page.
    //    value = "Invalid";
    //}
    /// <summary>
    /// primary constructor
    /// </summary>
    /// <param name="value">The string value that this is a wrapper for</param>
    private StringEnum(string value)
    {
        this.value = value;
    }

    /// <summary>
    /// Compares the StringEnum to another StringEnum, or to a string value.
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public override bool Equals(object obj)
    {
        if (obj is StringEnum)
        {
            return this.Equals((StringEnum)obj);
        }

        string otherString = obj as string;
        if (otherString != null)
        {
            return this.Equals(otherString);
        }

        throw new ArgumentException("obj is neither a StringEnum nor a String");
    }

    /// <summary>
    /// Strongly typed equals method.
    /// </summary>
    /// <param name="other">Another StringEnum to compare this object to.</param>
    /// <returns>True if the objects are equal.</returns>
    public bool Equals(StringEnum other)
    {
        return value == other.value;
    }

    /// <summary>
    /// Equals method typed to a string.
    /// </summary>
    /// <param name="other">A string to compare this object to.  
    /// There must be a Group associated with that string.</param>
    /// <returns>True if 'other' represents the same Group as 'this'.</returns>
    public bool Equals(string other)
    {
        return value == other;
    }

    /// <summary>
    /// Overridden equals operator, for convenience.
    /// </summary>
    /// <param name="first"></param>
    /// <param name="second"></param>
    /// <returns>True if the objects are equal.</returns>
    public static bool operator ==(StringEnum first, StringEnum second)
    {
        return object.Equals(first, second);
    }

    public static bool operator !=(StringEnum first, StringEnum second)
    {
        return !object.Equals(first, second);
    }

    /// <summary>
    /// Properly overrides GetHashCode so that it returns the hash of the wrapped string.
    /// </summary>
    /// <returns></returns>
    public override int GetHashCode()
    {
        return value.GetHashCode();
    }

    /// <summary>
    /// returns the internal string that this is a wrapper for.
    /// </summary>
    /// <param name="stringEnum"></param>
    /// <returns></returns>
    public static implicit operator string(StringEnum stringEnum)
    {
        return stringEnum.value;
    }

    /// <summary>
    /// Parses a string and returns an instance that corresponds to it.
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public static StringEnum Parse(string input)
    {
        return AllValues.Where(item => item.value == input).FirstOrDefault();
    }

    /// <summary>
    /// Syntatic sugar for the Parse method.
    /// </summary>
    /// <param name="other"></param>
    /// <returns></returns>
    public static explicit operator StringEnum(string other)
    {
        return Parse(other);
    }

    /// <summary>
    /// A string representation of this object.
    /// </summary>
    /// <returns></returns>
    public override string ToString()
    {
        return value;
    }
}
于 2012-11-01T17:30:01.040 回答