比方說,我有這樣的方法得到的字符串作爲一個擴展參數:是否有可能從擴展方法獲取屬性的名稱
private static List<string> ValidationErrors = new List<string>();
private static void ErrorCheck<T>(this string str)
{
if (string.IsNullOrEmpty(str))
{
// This just returns "str"
// Instead of property name (see "How I use" section")
ValidationErrors.Add(typeof(T).Namespace + "[" + nameof(str) + "]");
}
}
這是我如何使用它:
Car.Color.ErrorCheck<Car>();
在哪裏汽車對象的顏色只是字符串屬性。所以我想要的是在我的擴展方法中使用「Color」而不是「str」。
任何想法,我可以做到這一點?
'Car.Color.ErrorCheck()',你可以不匹配類型的事實(如'Car.Color.ErrorCheck ()')應該線索你在你當前的系統是有缺陷的。將字符串作爲參數傳遞時,無法知道該字符串最初來自哪裏(在您的案例中爲「Car.Color」)。一個更加可行的解決方案(並且不太容易出現開發人員錯誤)就像'Car.ErrorCheck(x => x.Color)' –
Flater
是的,謝謝!在評論之前沒有想到這一點。似乎是合法的。 –