gpt4 book ai didi

C# 属性作为数组表示法

转载 作者:太空狗 更新时间:2023-10-29 22:24:27 25 4
gpt4 key购买 nike

使用 JavaScript 可以使用点符号或数组符号访问对象。

var myArray = {e1:"elem1",e2:"elem2",e3:"elem3",e4:"elem4"};
var val1 = myArray["e1"];
var val2 = myArray.e1;

是否可以使用 C# 完成此操作?

这是我尝试过的:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection frmVals)
{
string value;
Owner owner = new Owner();

foreach (var key in frmVals.AllKeys)
{
value = frmVals[key];
owner[key] = value;
}
}

最佳答案

虽然没有办法用 C# 完全做到这一点。您可以通过多种方式更改代码以实现您的目标。首先,您可以像这样使用字典:

var something = new Dictionary<string, object>() {
{ "property", "value"},
{ "property1", 1}
};
foreach (var keyVal in something) {
var property = keyVal.Key;
var propertyValue = keyVal.Value;
}

另一种选择是动态执行:

dynamic somethingDyn = new System.Dynamic.ExpandoObject();
somethingDyn.property = "value";
somethingDyn.property1 = 1;

var somethingDynDict = (IDictionary<string, object>)somethingDyn;
var propValue = somethingDyn["property"];

foreach (var keyVal in somethingDynDict) {
var property = keyVal.Key;
var propertyValue = keyVal.Value;
}

如果您需要遍历强类型对象的属性,您可以使用反射:

var owner = new Metis.Domain.User();
var properties = owner.GetType().GetProperties();
foreach (var prop in properties) {
object value = prop.GetValue(owner, null);
}

关于C# 属性作为数组表示法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4831242/

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