【发布时间】:2019-03-12 20:57:03
【问题描述】:
我这里有以下类示例:
public class Foo
{
public int Id { get; set; }
public string Bar { get; set; }
public string FooBar { get; set; }
public string Fizz { get; set; }
public string Buzz { get; set; }
public static Foo Create(int id, string property, string value)
{
return new Foo
{
Id = id,
};
}
}
但是,现在,如果属性名称为 Bar,我只想将 Bar 设置为类的 Create 方法中的值。所以我看了一下C# setting/getting the class properties by string name,但我无法让它在 create 方法中工作。 Setting a property by reflection with a string value 也是如此,所以我有点迷路了。
作为一点澄清。我可以让上述方法在 create 中起作用,但在 return 中不起作用,这是它需要起作用的地方。
下面的解决方案目前似乎对我们有用,但是,我认为它可以进行优化。
public class Foo
{
public int Id { get; set; }
public string Bar { get; set; }
public string FooBar { get; set; }
public string Fizz { get; set; }
public string Buzz { get; set; }
public static Foo Create(int id, string property, string value)
{
return new Foo
{
WebshopCustomerId = webshopCustomerId,
Bar = (typeof(Foo)).GetProperty(property).Name == "Bar" ? value : null,
FooBar = (typeof(Foo)).GetProperty(property).Name == "FooBar" ? value : null,
Fizz = (typeof(Foo)).GetProperty(property).Name == "Fizz" ? value : null,
Buzz = (typeof(Foo)).GetProperty(property).Name == "Buzz" ? value : null,
};
}
}
【问题讨论】:
-
如果你不能让它工作,请告诉我们你做了什么......我们也许可以帮助你解决它
-
我建议不要使用反射来解决这个问题。而是将这些属性放入字典中,这样您就不必每次添加新属性时都重新编译。
-
@Filburt 属性是相当静态的,当它们发生变化时,我们也需要在其他地方进行更改。所以这不会是一个问题。另外,我们将它放在一个类中的原因是为了以后序列化。
-
你为什么需要它?你想解决哪个问题?
-
它看起来仍然像一个反模式,似乎有一个类依赖于在它的构造函数中设置的属性。我猜你的实际课程不仅有 4 个属性,而且还有更多。否则你可以简单地拥有 4 个重载构造函数。
标签: c# reflection