如何在C#中转换为泛型参数?
我正在尝试编写一个通用方法,用于以强类型方式获取如何在C#中转换为泛型参数?,c#,generics,casting,linq-to-xml,xelement,C#,Generics,Casting,Linq To Xml,Xelement,我正在尝试编写一个通用方法,用于以强类型方式获取XElement值。以下是我所拥有的: public static class XElementExtensions { public static XElement GetElement(this XElement xElement, string elementName) { // Calls xElement.Element(elementName) and returns that xElement (wit
XElement
值。以下是我所拥有的:
public static class XElementExtensions
{
public static XElement GetElement(this XElement xElement, string elementName)
{
// Calls xElement.Element(elementName) and returns that xElement (with some validation).
}
public static TElementType GetElementValue<TElementType>(this XElement xElement, string elementName)
{
XElement element = GetElement(xElement, elementName);
try
{
return (TElementType)((object) element.Value); // First attempt.
}
catch (InvalidCastException originalException)
{
string exceptionMessage = string.Format("Cannot cast element value '{0}' to type '{1}'.", element.Value,
typeof(TElementType).Name);
throw new InvalidCastException(exceptionMessage, originalException);
}
}
}
调用GetElementValue
时,我得到以下异常:
System.InvalidCastException:无法将元素值“5”强制转换为类型“Int32”
我是否必须分别处理每个强制转换案例(或至少是数字案例)?在C#中,不能将string对象强制转换为Int32。例如,此代码产生编译错误:
如果您需要这些功能,请尝试使用或和方法
是的,您应该单独处理数字转换,如果您想将字符串转换为int。您不能将
字符串
隐式或显式转换为Int32
,您需要使用Int32
的解析
或TryParse
方法。您可能会创建一些漂亮的扩展方法,例如:
using System;
using System.Diagnostics;
using System.Globalization;
using System.Text;
/// <summary>
/// Provides extension methods for strings.
/// </summary>
public static class StringExtensions
{
#region Methods
/// <summary>
/// Converts the specified string to a <see cref="Boolean"/>
/// </summary>
/// <param name="string">The string to convert.</param>
/// <returns>The specified string as a <see cref="Boolean"/>.</returns>
public static bool AsBoolean(this string @string)
{
return bool.Parse(@string);
}
/// <summary>
/// Converts the specified string to a <see cref="Boolean"/> using TryParse.
/// </summary>
/// <remarks>
/// If the specified string cannot be parsed, the default value (if valid) or false is returned.
/// </remarks>
/// <param name="string">The string to convert.</param>
/// <param name="default">The default value for if the value cannot be parsed.</param>
/// <returns>The specified string as a <see cref="DateTime"/>.</returns>
public static bool AsBooleanNonStrict(this string @string, bool? @default = null)
{
bool @bool;
if ((!string.IsNullOrEmpty(@string)) && bool.TryParse(@string, out @bool))
return @bool;
if (@default.HasValue)
return @default.Value;
return false;
}
/// <summary>
/// Converts the specified string to a <see cref="DateTime"/>
/// </summary>
/// <param name="string">The string to convert.</param>
/// <returns>The specified string as a <see cref="DateTime"/>.</returns>
public static DateTime AsDateTime(this string @string)
{
return DateTime.Parse(@string);
}
/// <summary>
/// Converts the specified string to a <see cref="DateTime"/> using TryParse.
/// </summary>
/// <remarks>
/// If the specified string cannot be parsed, <see cref="DateTime.MinValue"/> is returned.
/// </remarks>
/// <param name="string">The string to convert.</param>
/// <param name="default">The default value for if the value cannot be parsed.</param>
/// <returns>The specified string as a <see cref="DateTime"/>.</returns>
public static DateTime AsDateTimeNonStrict(this string @string, DateTime? @default = null)
{
DateTime datetime;
if ((!string.IsNullOrEmpty(@string)) && DateTime.TryParse(@string, out datetime))
return datetime;
if (@default.HasValue)
return @default.Value;
return DateTime.MinValue;
}
/// <summary>
/// Converts the specified string to a <see cref="TEnum"/>
/// </summary>
/// <param name="string">The string to convert.</param>
/// <returns>The specified string as a <see cref="TEnum"/>.</returns>
public static TEnum AsEnum<TEnum>(this string @string) where TEnum : struct
{
return (TEnum)Enum.Parse(typeof(TEnum), @string);
}
/// <summary>
/// Converts the specified string to a <see cref="TEnum"/>
/// </summary>
/// <param name="string">The string to convert.</param>
/// <returns>The specified string as a <see cref="TEnum"/>.</returns>
public static TEnum AsEnumNonStrict<TEnum>(this string @string, TEnum @default) where TEnum : struct
{
TEnum @enum;
if ((!string.IsNullOrEmpty(@string)) && Enum.TryParse(@string, out @enum))
return @enum;
return @default;
}
/// <summary>
/// Converts the specified string to a <see cref="Int32"/>
/// </summary>
/// <param name="string">The string to convert.</param>
/// <returns>The specified string as a <see cref="Int32"/>.</returns>
public static int AsInteger(this string @string)
{
return int.Parse(@string);
}
/// <summary>
/// Converts the specified string to a <see cref="Int32"/> using TryParse.
/// </summary>
/// <remarks>
/// If the specified string cannot be parsed, the default value (if valid) or 0 is returned.
/// </remarks>
/// <param name="string">The string to convert.</param>
/// <param name="default">The default value for if the value cannot be parsed.</param>
/// <returns>The specified string as a <see cref="Int32"/>.</returns>
public static int AsIntegerNonStrict(this string @string, int? @default = null)
{
int @int;
if ((!string.IsNullOrEmpty(@string)) && int.TryParse(@string, out @int))
return @int;
if (@default.HasValue)
return @default.Value;
return 0;
}
/// <summary>
/// Converts the specified string to a <see cref="bool"/>
/// </summary>
/// <param name="string">The string to convert.</param>
/// <returns>The specified string as a <see cref="DateTime"/>.</returns>
public static bool? AsNullableBolean(this string @string)
{
bool @bool;
if ((string.IsNullOrEmpty(@string)) || !bool.TryParse(@string, out @bool))
return null;
return @bool;
}
/// <summary>
/// Converts the specified string to a <see cref="DateTime"/>
/// </summary>
/// <param name="string">The string to convert.</param>
/// <returns>The specified string as a <see cref="DateTime"/>.</returns>
public static DateTime? AsNullableDateTime(this string @string)
{
DateTime dateTime;
if ((string.IsNullOrEmpty(@string)) || !DateTime.TryParse(@string, out dateTime))
return null;
return dateTime;
}
/// <summary>
/// Converts the specified string to a <see cref="DateTime"/>
/// </summary>
/// <param name="string">The string to convert.</param>
/// <returns>The specified string as a <see cref="DateTime"/>.</returns>
public static TEnum? AsNullableEnum<TEnum>(this string @string) where TEnum : struct
{
TEnum @enum;
if ((string.IsNullOrEmpty(@string)) || !Enum.TryParse(@string, out @enum))
return null;
return @enum;
}
/// <summary>
/// Converts the specified string to a <see cref="Int32"/>
/// </summary>
/// <param name="string">The string to convert.</param>
/// <returns>The specified string as a <see cref="Int32"/>.</returns>
public static int? AsNullableInteger(this string @string)
{
int @int;
if ((string.IsNullOrEmpty(@string)) || !int.TryParse(@string, out @int))
return null;
return @int;
}
#endregion
}
使用系统;
使用系统诊断;
利用制度全球化;
使用系统文本;
///
///提供字符串的扩展方法。
///
公共静态类扩展
{
#区域方法
///
///将指定的字符串转换为
///
///要转换的字符串。
///指定的字符串作为一个字符串。
公共静态布尔值为布尔值(此字符串@string)
{
返回bool.Parse(@string);
}
///
///使用TryParse将指定的字符串转换为字符串。
///
///
///如果无法分析指定的字符串,则返回默认值(如果有效)或false。
///
///要转换的字符串。
///如果无法分析该值,则为的默认值。
///指定的字符串作为一个字符串。
公共静态bool AsBooleanNonStrict(此字符串@string,bool?@default=null)
{
bool@bool;
if((!string.IsNullOrEmpty(@string))&&bool.TryParse(@string,out@bool))
返回@bool;
如果(@default.HasValue)
return@default.Value;
返回false;
}
///
///将指定的字符串转换为
///
///要转换的字符串。
///指定的字符串作为一个字符串。
公共静态DateTime AsDateTime(此字符串@string)
{
return DateTime.Parse(@string);
}
///
///使用TryParse将指定的字符串转换为字符串。
///
///
///如果无法分析指定的字符串,则返回。
///
///要转换的字符串。
///如果无法分析该值,则为的默认值。
///指定的字符串作为一个字符串。
公共静态DateTime AsDateTimeNonStrict(此字符串@string,DateTime?@default=null)
{
日期时间日期时间;
if((!string.IsNullOrEmpty(@string))&&DateTime.TryParse(@string,out-DateTime))
返回日期时间;
如果(@default.HasValue)
return@default.Value;
return DateTime.MinValue;
}
///
///将指定的字符串转换为
///
///要转换的字符串。
///指定的字符串作为一个字符串。
公共静态TEnum-AsEnum(此字符串@string),其中TEnum:struct
{
return(TEnum)Enum.Parse(typeof(TEnum),@string);
}
///
///将指定的字符串转换为
///
///要转换的字符串。
///指定的字符串作为一个字符串。
公共静态TEnum AsEnumNonStrict(此字符串@string,TEnum@default),其中TEnum:struct
{
TEnum@enum;
if((!string.IsNullOrEmpty(@string))&&Enum.TryParse(@string,out@Enum))
返回@enum;
返回@default;
}
///
///将指定的字符串转换为
///
///要转换的字符串。
///指定的字符串作为一个字符串。
公共静态int-AsInteger(此字符串@string)
{
返回int.Parse(@string);
}
///
///使用TryParse将指定的字符串转换为字符串。
///
///
///如果无法分析指定的字符串,则返回默认值(如果有效)或0。
///
///要转换的字符串。
///如果无法分析该值,则为的默认值。
///指定的字符串作为一个字符串。
公共静态int-AsIntegerNonStrict(此字符串@string,int?@default=null)
{
int@int;
if((!string.IsNullOrEmpty(@string))&&int.TryParse(@string,out@int))
返回@int;
如果(@default.HasValue)
return@default.Value;
返回0;
}
///
///将指定的字符串转换为
///
///要转换的字符串。
///指定的字符串作为一个字符串。
公共静态bool?AsNullableBolean(此字符串@string)
{
bool@bool;
if((string.IsNullOrEmpty(@string))| |!bool.TryParse(@string,out@bool))
返回null;
返回@bool;
}
///
///将指定的字符串转换为
///
///要转换的字符串。
///指定的字符串作为一个字符串。
公共静态日期时间?AsNullableDateTime(此字符串@string)
{
日期时间日期时间;
if((string.IsNullOrEmpty(@string))| |!DateTime.TryParse(@string,out DateTime))
返回null;
返回日期时间;
}
///
///将指定的字符串转换为
///
///要转换的字符串。
///指定的字符串作为一个字符串。
公共静态TEnum?AsNullableEnum(此字符串@string),其中TEnum:struct
{
TEnum@enum;
如果
string a = "123.4";
int x = (int) a;
using System;
using System.Diagnostics;
using System.Globalization;
using System.Text;
/// <summary>
/// Provides extension methods for strings.
/// </summary>
public static class StringExtensions
{
#region Methods
/// <summary>
/// Converts the specified string to a <see cref="Boolean"/>
/// </summary>
/// <param name="string">The string to convert.</param>
/// <returns>The specified string as a <see cref="Boolean"/>.</returns>
public static bool AsBoolean(this string @string)
{
return bool.Parse(@string);
}
/// <summary>
/// Converts the specified string to a <see cref="Boolean"/> using TryParse.
/// </summary>
/// <remarks>
/// If the specified string cannot be parsed, the default value (if valid) or false is returned.
/// </remarks>
/// <param name="string">The string to convert.</param>
/// <param name="default">The default value for if the value cannot be parsed.</param>
/// <returns>The specified string as a <see cref="DateTime"/>.</returns>
public static bool AsBooleanNonStrict(this string @string, bool? @default = null)
{
bool @bool;
if ((!string.IsNullOrEmpty(@string)) && bool.TryParse(@string, out @bool))
return @bool;
if (@default.HasValue)
return @default.Value;
return false;
}
/// <summary>
/// Converts the specified string to a <see cref="DateTime"/>
/// </summary>
/// <param name="string">The string to convert.</param>
/// <returns>The specified string as a <see cref="DateTime"/>.</returns>
public static DateTime AsDateTime(this string @string)
{
return DateTime.Parse(@string);
}
/// <summary>
/// Converts the specified string to a <see cref="DateTime"/> using TryParse.
/// </summary>
/// <remarks>
/// If the specified string cannot be parsed, <see cref="DateTime.MinValue"/> is returned.
/// </remarks>
/// <param name="string">The string to convert.</param>
/// <param name="default">The default value for if the value cannot be parsed.</param>
/// <returns>The specified string as a <see cref="DateTime"/>.</returns>
public static DateTime AsDateTimeNonStrict(this string @string, DateTime? @default = null)
{
DateTime datetime;
if ((!string.IsNullOrEmpty(@string)) && DateTime.TryParse(@string, out datetime))
return datetime;
if (@default.HasValue)
return @default.Value;
return DateTime.MinValue;
}
/// <summary>
/// Converts the specified string to a <see cref="TEnum"/>
/// </summary>
/// <param name="string">The string to convert.</param>
/// <returns>The specified string as a <see cref="TEnum"/>.</returns>
public static TEnum AsEnum<TEnum>(this string @string) where TEnum : struct
{
return (TEnum)Enum.Parse(typeof(TEnum), @string);
}
/// <summary>
/// Converts the specified string to a <see cref="TEnum"/>
/// </summary>
/// <param name="string">The string to convert.</param>
/// <returns>The specified string as a <see cref="TEnum"/>.</returns>
public static TEnum AsEnumNonStrict<TEnum>(this string @string, TEnum @default) where TEnum : struct
{
TEnum @enum;
if ((!string.IsNullOrEmpty(@string)) && Enum.TryParse(@string, out @enum))
return @enum;
return @default;
}
/// <summary>
/// Converts the specified string to a <see cref="Int32"/>
/// </summary>
/// <param name="string">The string to convert.</param>
/// <returns>The specified string as a <see cref="Int32"/>.</returns>
public static int AsInteger(this string @string)
{
return int.Parse(@string);
}
/// <summary>
/// Converts the specified string to a <see cref="Int32"/> using TryParse.
/// </summary>
/// <remarks>
/// If the specified string cannot be parsed, the default value (if valid) or 0 is returned.
/// </remarks>
/// <param name="string">The string to convert.</param>
/// <param name="default">The default value for if the value cannot be parsed.</param>
/// <returns>The specified string as a <see cref="Int32"/>.</returns>
public static int AsIntegerNonStrict(this string @string, int? @default = null)
{
int @int;
if ((!string.IsNullOrEmpty(@string)) && int.TryParse(@string, out @int))
return @int;
if (@default.HasValue)
return @default.Value;
return 0;
}
/// <summary>
/// Converts the specified string to a <see cref="bool"/>
/// </summary>
/// <param name="string">The string to convert.</param>
/// <returns>The specified string as a <see cref="DateTime"/>.</returns>
public static bool? AsNullableBolean(this string @string)
{
bool @bool;
if ((string.IsNullOrEmpty(@string)) || !bool.TryParse(@string, out @bool))
return null;
return @bool;
}
/// <summary>
/// Converts the specified string to a <see cref="DateTime"/>
/// </summary>
/// <param name="string">The string to convert.</param>
/// <returns>The specified string as a <see cref="DateTime"/>.</returns>
public static DateTime? AsNullableDateTime(this string @string)
{
DateTime dateTime;
if ((string.IsNullOrEmpty(@string)) || !DateTime.TryParse(@string, out dateTime))
return null;
return dateTime;
}
/// <summary>
/// Converts the specified string to a <see cref="DateTime"/>
/// </summary>
/// <param name="string">The string to convert.</param>
/// <returns>The specified string as a <see cref="DateTime"/>.</returns>
public static TEnum? AsNullableEnum<TEnum>(this string @string) where TEnum : struct
{
TEnum @enum;
if ((string.IsNullOrEmpty(@string)) || !Enum.TryParse(@string, out @enum))
return null;
return @enum;
}
/// <summary>
/// Converts the specified string to a <see cref="Int32"/>
/// </summary>
/// <param name="string">The string to convert.</param>
/// <returns>The specified string as a <see cref="Int32"/>.</returns>
public static int? AsNullableInteger(this string @string)
{
int @int;
if ((string.IsNullOrEmpty(@string)) || !int.TryParse(@string, out @int))
return null;
return @int;
}
#endregion
}
Convert.ChangeType(element.Value, typeof(TElementType))
((IConvertible)mystring).ToInt32(null);
return (TElementType)((object) element.Value);
return (TElementType) Convert.ChangeType(element.Value, typeof (T));