我試圖在我的擴展方法中獲取呼叫屬性的名稱,以便在發生例外時使用它。
我的擴展方法如下所示:
/// <summary>
/// Parse string to value of T
/// Can throw on Default or Exception
/// </summary>
/// <typeparam name="T">Type to Convert to</typeparam>
/// <param name="value">value for conversion</param>
/// <param name="throwOnDefault">set <see langword="true"/>for throw on Exception or Default</param>
/// <returns></returns>
/// <exception cref="NotSupportedException">If string can't be converted</exception>
/// <exception cref="Exception">If converted value is defaut</exception>
public static T ParseOrDefault<T>(this string value, bool throwOnDefault = false, [CallerMemberName]string methodName = "")
{
if (Nullable.GetUnderlyingType(typeof(T)) == null && value.IsNullOrWhitespace())
throw new ArgumentNullException(value, $"{methodName} : value of string is null");
System.ComponentModel.TypeConverter converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(T));
try
{
var converted = (T)converter.ConvertFromString(null, System.Globalization.CultureInfo.InvariantCulture, value);
var type = converted?.GetType();
if (type != null && type.IsValueType)
{
var defaultValue = Activator.CreateInstance(type);
return !value.Equals(defaultValue) ? converted : throw new Exception("Converted value is default value");
}
else
{
return converted;
}
}
catch (Exception)
{
if (throwOnDefault)
throw;
else
return default;
}
}
我是這樣使用它的:
var parsedVal = property.ParseOrDefault<Guid>();
或像這樣:
public void SomeMethod (RequestModel request)
{
Dto dto = new()
{
intProperty = request.IntValue.ParseOrDefault<int>(), // IntValue in the requestObject is a string
guidProperty = request.GuidValue.ParseOrDefault<Guid>() // GuidValue in the requestObject is a string
}
}
我已經嘗試了以下鏈接中的一些建議,但它們都只是讓我知道呼叫方法的名稱,而不是屬性的名稱。
如何通過反射獲取當前屬性名稱?
我的目標是獲取方法和屬性,使我的例外看起來像這樣:
if (Nullable.GetUnderlyingType(typeof(T)) == null && value.IsNullOrWhitespace())
throw new ArgumentNullException(value, $"{methodName} : value of {propertyName} is null");
uj5u.com熱心網友回復:
[CallerMemberName]將為您提供呼叫您的擴展方法的方法/屬性的名稱。在您的示例中,那將是SomeMethod.
如果您可以更新到 C# 10,則可以改用該[CallerArgumentExpression]屬性。
public static T ParseOrDefault<T>(this string value, bool throwOnDefault = false, [CallerArgumentExpression("value")] string memberName = "")
對于request.IntValue.ParseOrDefault<int>(),memberName將被設定為request.IntValue。
如果您使用的是 .NET Framework,只要您使用的是最新的編譯器,您仍然可以使用這種方法。您只需要手動定義屬性類。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/371687.html
上一篇:從Selenium中的下拉串列中選擇——元素不可見(Python)
下一篇:資料模板中的用戶控制元件未顯示
