当字符串为 null 时扩展到 return DBnull

Extension to return DBnull when a string is null

我正在尝试在 C# 中为字符串创建自定义扩展,请查看下面的示例,我的要求是当字符串无效时此扩展应该 return DBNull,否则它应该 return 文本。这该怎么做。 My Factory.IsValidString 具有确定字符串是否有效的所有检查。

public static string DBString(this string Text)
{
    return (!Factory.ISValidString(Text)) ? DBNull: Text;
}

正如 Evk 在对您的 post 的评论中所说:

DBNull and string are different types, and they have no common parent type except object, so your extension method should return object and not string

所以你应该像下面这样重构你的扩展方法:

public static object DBString(this string Text)
{
    return (!Factory.ISValidString(Text)) ? (object)DBNull.Value: Text;
}

请记住,您可能需要将返回的对象转换为 stringDBNull,具体取决于使用它的代码的作用。

不使用 DBNull.Value 而是使用 SqlString.Null 并将 return 类型更改为 SqlString 并且此处不需要转换,因为它存在 [ 之间的隐式转换=14=] 和 SqlString:

public static SqlString DBString(this string Text)
{
    return (!Factory.ISValidString(Text)) ? SqlString.Null : Text;
}

此解决方案让调用者知道他正在处理 SqlString 类型,而不仅仅是可能包含任何内容的 object 类型。