WPF를 사용하면 INotifyPropertyChanged의 팬이되었습니다. 표현식을 사용하는 헬퍼를 사용하고 이름을 문자열로 반환합니다 (아래 예제 코드 참조). 그러나 매우 숙련 된 프로그래머가 볼 수있는 많은 응용 프로그램에서 원시 문자열을 처리하는 코드가 있습니다 (아래의 두 번째 예제 참조). 능숙하게는 표현을 사용하는 방법을 알고있는 MVP 유형을 의미합니다..net propertychange 알림 처리기 - 문자열 대 표현
내게있어, 쉬운 리팩터링 외에도 컴파일러가 실수를 포착 할 기회는 익스 프레스 접근법을 개선합니다. 제가 실종 된 원시 문자열을 사용하는 것에 대한 논쟁이 있습니까?
건배, Berryl
표현 도우미 예 : (일부 ViewModelBase 형 클래스)
public static string GetPropertyName<T>(Expression<Func<T, object>> propertyExpression)
{
Check.RequireNotNull<object>(propertyExpression, "propertyExpression");
switch (propertyExpression.Body.NodeType)
{
case ExpressionType.MemberAccess:
return (propertyExpression.Body as MemberExpression).Member.Name;
case ExpressionType.Convert:
return ((propertyExpression.Body as UnaryExpression).Operand as MemberExpression).Member.Name;
}
var msg = string.Format("Expression NodeType: '{0}' does not refer to a property and is therefore not supported",
propertyExpression.Body.NodeType);
Check.Require(false, msg);
throw new InvalidOperationException(msg);
}
원시 문자열 예제 코드 :
나에게 /// <summary>
/// Warns the developer if this object does not have
/// a public property with the specified name. This
/// method does not exist in a Release build.
/// </summary>
[Conditional("DEBUG"), DebuggerStepThrough]
public void VerifyPropertyName(string propertyName) {
// Verify that the property name matches a real,
// public, instance property on this object.
if (TypeDescriptor.GetProperties(this)[propertyName] == null) {
string msg = "Invalid property name: " + propertyName;
if (ThrowOnInvalidPropertyName) throw new Exception(msg);
else Debug.Fail(msg);
}
}
/// <summary>
/// Returns whether an exception is thrown, or if a Debug.Fail() is used
/// when an invalid property name is passed to the VerifyPropertyName method.
/// The default value is false, but subclasses used by unit tests might
/// override this property's getter to return true.
/// </summary>
protected virtual bool ThrowOnInvalidPropertyName { get; private set; }
입니까? – Berryl
오, 알겠습니다. 내가 직접 제공 한 코드 샘플에서 볼 수있다 :-) – Berryl
그래, 기본적으로 표현 자체로 평면으로 떨어지는 리플렉션 자체를 수행하는 대신, 실제로 더 많은 힘을 가지며 확장 성을 제공하는 TypeDescriptor 아키텍처를 사용한다. 얘기 했어. 당연히 이는 약간의 오버 헤드가 있습니다. –