0
我使用面向方面的編程來實現日誌記錄系統。所以,當方法被調用我攔截該呼叫,並獲得該功能:比較來自MethodInfo和IMethodInvocation的方法
private IEnumerable<ILogMessage> GetLogMessageFromAttribute(IMethodInvocation input)
{
List<ILogMessage> messages = new List<ILogMessage>();
var t = input.Target.GetType();
var method = t.GetMethods()
.FirstOrDefault(m => m.ToString() == input.MethodBase.ToString());
if (method != null)
{
var attributes = method.CustomAttributes
.Where(atr => atr.AttributeType == typeof(LogAttribute));
foreach (var atr in attributes)
{
var logAttributeInstance =
(LogAttribute)Attribute.GetCustomAttribute(method, typeof(LogAttribute));
messages.Add(MethodInfoTools.FillParametersDataInLogMessage(method, input,
logAttributeInstance.LogMessage));
}
}
return messages;
}
的方法可以通過自己的名字相提並論,但它也可以被重載和屬性可以爲這些方法不同。
var method = t.GetMethods()
.FirstOrDefault(m => m.ToString() == input.MethodBase.ToString());
這種方式很好,直到我試圖攔截通用的方法。在這種情況下的ToString()返回:
System.String TestMethod2[String](System.Collections.Generic.IEnumerable`1[System.String], System.String)
和
System.String TestMethod2[T](System.Collections.Generic.IEnumerable`1[System.String], T)
是否有某種方式來找出什麼是執行具體方法?