C# 地址变量由字符串c组成#

C# 地址变量由字符串c组成#,c#,C#,我有一个结构,有几个不同类型的属性。我需要一种方法,使用字符串将它们全部设置为值来处理属性,我知道我可以使用Switch Case语句,但我想知道是否有一种更快/更优雅的方法来实现这一点 public struct ExampleStruct { public string exampleProperty1 {get; set; } public int exampleProperty2 {get; set; } } public class ExampleClass {

我有一个结构,有几个不同类型的属性。我需要一种方法,使用字符串将它们全部设置为值来处理属性,我知道我可以使用Switch Case语句,但我想知道是否有一种更快/更优雅的方法来实现这一点

public struct ExampleStruct 
{
    public string exampleProperty1 {get; set; }
    public int exampleProperty2 {get; set; }
}
public class ExampleClass
{
    ExampleStruct e = new ExampleStruct();
    string s = "exampleProperty1";
    
    //
    // Is there a way to set exampleProperty1, using s to address it?
    // Something like e[s] = "foo"
    //
}

您可以使用
Type.GetProperty
方法,如文档中所述:

然后,可以按如下方式分配值:

string s = "exampleProperty1";
Type myType=typeof(ExampleStruct);
PropertyInfo myPropInfo = myType.GetProperty(s);
ExampleStruct e = new ExampleStruct();
myPropInfo.SetValue(e, "some value");

但是,您可能应该尝试为您的任务找到替代解决方案,因为使用反射来完成此任务有点过分。

我会使用字典来保存“属性”。我认为这是有用的
string s = "exampleProperty1";
Type myType=typeof(ExampleStruct);
PropertyInfo myPropInfo = myType.GetProperty(s);
ExampleStruct e = new ExampleStruct();
myPropInfo.SetValue(e, "some value");