C# 如何向构造的对象注入属性?
我有一个构造的对象,我想按名称和值注入属性。C# 如何向构造的对象注入属性?,c#,dependencies,unity-container,castle-windsor,code-injection,C#,Dependencies,Unity Container,Castle Windsor,Code Injection,我有一个构造的对象,我想按名称和值注入属性。 使用Unity/Castle windsor/Other framework有什么方法可以做到这一点吗?以下是使用.NET的方法: var myObject = new MyObject(); // do something var fields = typeof(MyObject).GetFields(); foreach (var field in fields) { // this is the name of the field
使用Unity/Castle windsor/Other framework有什么方法可以做到这一点吗?以下是使用.NET的方法:
var myObject = new MyObject();
// do something
var fields = typeof(MyObject).GetFields();
foreach (var field in fields) {
// this is the name of the field itself
var name = field.Name;
// this is the current value of the field
var val = field.GetValue(myObject );
// this sets the current field to the newValue
var newValue = 0;
field.SetValue(myObject, newValue);
}
比如说团结
IUnityContainer unityContainer=newunitycontainer();
unityContainer.RegisterType();
使用弹簧
或者通过反射,您可以实现从任何位置获取值
IUnityContainer unityContainer = new UnityContainer();
unityContainer.RegisterType<IClassB, ClassB>();
<object name="AnotherMovieFinder"
type="Spring.Examples.MovieFinder.ColonDelimitedMovieFinder, Spring.Examples.MovieFinder">
<constructor-arg index="0" value="movies.txt"/>
</object>