1
다른 알 수없는 모듈에서 개체를받는 클래스가있어서 개체에 대한 리플렉션을 수행하여 해당 데이터를 가져와 메서드를 호출해야합니다. 등개체 반영을 단순화하는 데 도움이되는 .NET ObjectReflector를 찾으십시오.
이 개체에 반영하는 코드를 단순화하기 위해, 내가 짓고 있어요이 클래스 :
namespace ApplicationCore.Presenters
{
public class SmartFormPresenter
{
public UserControl View { get; set; }
public string ShortName { get; set; }
public string LongName { get; set; }
public string FirstName { get; set; }
public int Age { get; set; }
public int AgePlusTwo { get; set; }
public SmartFormPresenter(object o)
{
SmartFormView smartFormView = new SmartFormView();
View = smartFormView;
smartFormView.DataContext = this;
ObjectReflector or = new ObjectReflector(o);
ShortName = or.GetObjectShortName();
LongName = or.GetObjectLongName();
FirstName = or.GetPropertyValue<string>("FirstName");
Age = or.GetPropertyValue<int>("Age");
AgePlusTwo = or.GetMethodValue<int>("GetAgeInTwoYears", null);
}
}
}
을 : 그래서 다음과 같습니다 좋은 깨끗한 코드를 가지고
using System;
namespace ApplicationCore.Helpers
{
class ObjectReflector
{
public object TheObject { get; set; }
public Type TheType { get; set; }
public ObjectReflector(object theObject)
{
TheObject = theObject;
TheType = theObject.GetType();
}
public string GetObjectShortName()
{
return TheObject.GetType().Name;
}
public string GetObjectLongName()
{
return TheObject.GetType().ToString();
}
public T GetPropertyValue<T>(string propertyName)
{
return (T)TheType.GetProperty(propertyName).GetValue(TheObject, null);
}
public T GetMethodValue<T>(string methodName, object[] parameters)
{
return (T)TheType.GetMethod(methodName).Invoke(TheObject, parameters);
}
}
}
그러나 지금 나는 방법을 만들 필요가있다. 밖으로 읽어 아닌 INT하지만 난 List<object>
을 가야 다음 등 "객체"에 반영거야 있도록 List<Contract>
그래서 나는이 전에 수행 된 것으로 생각하고있다 . .NET에서 ObjectReflector라고하는 도구 나 클래스의 모든 종류가있어 위에서 설명한 것처럼 개체의 반사를 단순화하는 데 도움이됩니까?
속성 및 메소드 이름을 직접 사용하지 않습니다. 대신 그들을 피하기 위해 linq 표현 트리를 사용하십시오. 이렇게하면 리팩토링이보다 안전 해집니다. –
XML 파일에 메소드와 속성 이름이 있는데, 알 수없는 객체에서 호출해야하는 문자열입니다. 이 경우에는 링 표현 나무가 어떻게 작동할까요? –
알 수없는 개체에서 컬렉션을 추출한 다음 컬렉션의 개체를 올바르게 반영하려는 경우 올바르게 이해했다면? –