C# 类对象 JavaScript 类似使用

在 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";


叮当猫咪
浏览 84回答 3
3回答

莫回无

您可以像这样在 C# 中使用反射:var prop=row.GetType().GetProperty("id");prop.SetValue(row,"id123");

郎朗坤

要回答您的确切问题,您可以创建一个自定义索引器: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 ,它会为您完成所有映射。

开满天机

C# 是一种强类型语言。这意味着一旦定义了类型,您就不能在运行时动态更改它*。您也不能像在 JavaScript 中那样使用 [] 访问对象的属性。因此,您无法在 C# 中实现您想要的。C# 方式很可能是直接通过row.id = "id23";. 在 C# 中,您总是在编译时知道对象上有哪些属性和方法可用。Dictionary如果您需要更多的灵活性,您还可以使用 aKeyValuePair或简单地使用 a List。*实际上有一个动态关键字可以为您提供某些功能 - 但在所有地方使用它并不常见。来自 JavaScript 我建议暂时忘记它。几乎总是有另一种“更像 C#”的方式。
打开App,查看更多内容
随时随地看视频慕课网APP