你不能做到這一點使用自動實現的屬性,正如其他人說。 Butyou可以使用抽象屬性和Castle DynamicProxy(或類似的)來做類似的事情。
例如,你可以有這樣的代碼:
public abstract class Foo : IWithSession
{
public IDictionary<string, object> Session { get; private set; }
protected Foo()
{
Session = new Dictionary<string, object>();
}
[Session]
public abstract int Id { get; set; }
}
,將真正實現getter和setter看起來像這樣的攔截器:
class SessionInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
var method = invocation.Method;
bool isGetter = method.IsSpecialName && method.Name.StartsWith("get_");
bool isSetter = method.IsSpecialName && method.Name.StartsWith("set_");
if (isGetter || isSetter)
{
string propertyName = method.Name.Substring(4);
var property = invocation.TargetType.GetProperty(propertyName);
bool hasSessionAttribute = property.GetCustomAttributes(typeof(SessionAttribute), false).Any();
if (hasSessionAttribute)
{
var session = ((IWithSession)invocation.InvocationTarget).Session;
if (isGetter)
{
invocation.ReturnValue = session[propertyName];
return;
}
else
{
session[propertyName] = invocation.Arguments[0];
return;
}
}
}
invocation.Proceed();
}
}
會盡量做到一些事情,謝謝指出方向。 –