为了账号安全,请及时绑定邮箱和手机立即绑定

C# 类对象 JavaScript 类似使用

C# 类对象 JavaScript 类似使用

C#
叮当猫咪 2022-11-22 16:39:53
在 C# 中,我定义了一个类对象,如下所示:public class Row    {        public string id { get; set; }        public string full_name { get; set; }        public string email { get; set; }    } 接下来我可以像这样使用它:Row row = new Row();然后做这样的事情来设置一个值:row.id = "id123";如何制作某种类型的“动态”参考?这不起作用:string col = "id";  row[col] = "id123";
查看完整描述

3 回答

?
莫回无

TA贡献1865条经验 获得超7个赞

您可以像这样在 C# 中使用反射:


var prop=row.GetType().GetProperty("id");

prop.SetValue(row,"id123");


查看完整回答
反对 回复 2022-11-22
?
郎朗坤

TA贡献1921条经验 获得超9个赞

要回答您的确切问题,您可以创建一个自定义索引器:


public object this[string key]

{

    get

    {

        switch(key)

        {

             case nameof(id): return id;

             case nameof(full_name): return full_name;

             case nameof(email): return email;

             default: throw new ArgumentOutOfRangeException();

        }

    }      

    set

    {

        switch(key)

        {

             case nameof(id):

                 id = value.ToString();

                 break;

             case nameof(full_name):

                 full_name = value.ToString();

                 break;

             case nameof(email):

                 email = value.ToString();

                 break;

             default: throw new ArgumentOutOfRangeException();

        }

    }

}


public void Foo()

{

    var row = new Row();

    row["id"] = "Foo";

}

或者你像 TSungur 回答的那样使用反射:


public object this[string key]

{

    get

    {

        var prop = GetType().GetProperty(key);

        return prop.GetValue(this);

    }      

    set

    {

        var prop = GetType().GetProperty(key);

        prop.SetValue(this, value);

    }

}

但是,如果我是你,我会审查你当前的图书馆设计。可能您想使用像Entity Framework这样的 ORM ,它会为您完成所有映射。


查看完整回答
反对 回复 2022-11-22
?
开满天机

TA贡献1786条经验 获得超12个赞

C# 是一种强类型语言。这意味着一旦定义了类型,您就不能在运行时动态更改它*。您也不能像在 JavaScript 中那样使用 [] 访问对象的属性。因此,您无法在 C# 中实现您想要的。C# 方式很可能是直接通过row.id = "id23";. 在 C# 中,您总是在编译时知道对象上有哪些属性和方法可用。Dictionary如果您需要更多的灵活性,您还可以使用 aKeyValuePair或简单地使用 a List

*实际上有一个动态关键字可以为您提供某些功能 - 但在所有地方使用它并不常见。来自 JavaScript 我建议暂时忘记它。几乎总是有另一种“更像 C#”的方式。


查看完整回答
反对 回复 2022-11-22
  • 3 回答
  • 0 关注
  • 81 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信