gpt4 book ai didi

c# - 这种技术在 C# 中称为什么?

转载 作者:太空狗 更新时间:2023-10-30 00:14:06 24 4
gpt4 key购买 nike

我想在某些属性中定义一个对象,但我不知道该怎么做。像这样:

var obj = ...;
obj["prop1"] = "Property 1";
obj["prop2"] = "Property 2";

我可以创建一个字符串来获取其中之一:

string temp = "prop1";
string prop1 = obj[temp];

在 C# 中可以吗?

最佳答案

你想要的是字典:

var obj = new Dictionary<string, string>();

obj.Add("prop1", "Property1");

Console.WriteLine(obj["prop1"]);

如果属性定义明确,我建议创建一个类:

public class MyObject
{
public string Prop1;
public string Prop2;
}

然后你可以这样做:

var obj = new MyObject
{
Prop1 = "Property 1",
Prop2 = "Property 2"
};

Console.WriteLine(obj.Prop1); //Will echo out 'Property 1'

关于c# - 这种技术在 C# 中称为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33304905/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com