C#:为数组中的每个值生成单独的变量

时间:2017-04-17 04:15:11

标签: c# arrays variables

如何将字符串数组Joe, Ben, Carl中的每个元素存储到单独的变量中,以便GuestA为Joe,GuestB为Ben,而GuestC为Carl而不使用字典? (请注意,变量按字母顺序排列)

3 个答案:

答案 0 :(得分:2)

不确定您为什么要这样做,但如果从字面上理解,此代码会回答您的问题。

string[] list = new string[] {"Joe","Ben","Carl"};
string GuestA = list[0];
string GuestB = list[1];
string GuestC = list[2];

有些东西告诉我还有其他要求,你无法明确表达。

答案 1 :(得分:0)

假设您已宣布GuestAGuestBGuestC,您可以像这样使用反思

private string GuestA;
private string GuestB;
private string GuestC;

private void button1_Click(object sender, EventArgs e)
{
    string variableName;
    string[] values = {"Joe", "Ben", "Carl" };
    for(int i = 0; i < values.Length; i++)
    {
        variableName = "Guest" + Convert.ToChar(65 + i).ToString();
        System.Reflection.FieldInfo fi = this.GetType().GetField(variableName, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
        if (fi != null)
        {
            fi.SetValue(this, values[i]);
        }
    }
}

虽然我怀疑这并不是你所用的,因为你使用了&#34; Generate&#34;在你的头衔。

答案 2 :(得分:0)

你不能使用像refrence类型这样的字符串,但是你可以通过运算符重载来模拟引用行为,但在这种情况下出现了一个大问题:无法重载赋值运算符,在代码下面通过类似属性的样式绕过它。但我认为你可以尝试像Guest guestD = tempGuest = "Joe Ho";这样的双重任务(不确定)。

public class ReferencedStringExample
{
    public void Wrong()
    {
        string GuestA = "Joe",
            GuestB = "Ben",
            GuestC = "Carl";

        var array = new string[]
        {
            GuestA,
            GuestB,
            GuestC
        };

        GuestA = "Joe Ho";

        Debug.Assert(GuestA == array[0]);            
    }

    public void Right()
    {
        Guest GuestA = "Joe",
            GuestB = "Ben",
            GuestC = "Carl";

        var array = new Guest[]
        {
            GuestA,
            GuestB,
            GuestC
        };

        GuestA.Val("Joe Ho");

        Debug.Assert(GuestA == array[0]);
        Debug.Assert(GuestA == "Joe Ho");

        GuestA = "Joe Ho";
        Debug.Assert(GuestA != array[0]);
        Debug.Assert(GuestA == "Joe Ho");
    }

    public class Guest
    {
        string value;

        public static implicit operator string(Guest g)
        {
            return g.value;
        }

        public static implicit operator Guest(string s)
        {
            return new Guest() { value = s };
        }
        public Guest Val(string s)
        {
            this.value = s;
            return this;
        }

        public override bool Equals(object obj)
        {
            Guest guest = obj as Guest;
            return guest.value == this.value;
        }
        public override int GetHashCode()
        {
            return (value ?? string.Empty).GetHashCode();
        }
    }
}