在許多情況下,人們需要一種表達,參數,聲明等。例如名稱:如何獲得C#中的任何表達式作爲字符串?
public abstract void Log(string methodName, string parameterName, string message);
public void FooMethod(string value)
{
if (value == null)
{
this.Log("FooMethod", "value", "The value must be whatever...");
throw new ArgumentNullException("value");
}
if (value.Length < 5)
{
this.Log("FooMethod", "value.Length", "The value length must be whatever...");
throw new ArgumentException("value");
}
}
是否有可以像使用自動獲得這些字符串文字像例如與關鍵字的任何方式typeof(string)
? 還是有一種基於反射的簡單和高性能的方法?
我不是在尋找一種方法來檢查和記錄這個參數(這實際上只是一個例子)。我正在尋找一種方法來獲取部分代碼,如string
。
下會更準確,可以通過編譯器進行檢查,並重構代碼時,也將考慮:
public void FooMethod(string value)
{
if (value == null)
{
this.Log(literal(this.FooMethod), literal(value), "The parameter '" + literal(value) + "' must be whatever...");
throw new ArgumentNullException(literal(value));
}
if (value.Length < 5)
{
this.Log(literal(this.FooMethod), literal(value.Length), "The value length must be whatever...");
throw new ArgumentException(literal(value));
}
}
您的第二個示例是僞造的。沒有代碼會在'throw'後執行。 – leppie
感謝您的建議。我改變了這個例子。 –