c# - 当字符串为 null 时返回 DBnull 的扩展

标签 c# string extension-methods

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

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

最佳答案

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

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,具体取决于使用它的代码正在做什么。

关于c# - 当字符串为 null 时返回 DBnull 的扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50061543/

相关文章:

c# - 将依赖属性绑定(bind)到当前 DataContext 属性

java - Java如何存储字符串以及子字符串在内部如何工作?

python - “合并”列表中元素上的 2 个数据框? - 双 key

python - 为什么我在 string.replace() 上得到 "AttributeError: ' 模块对象没有属性 'replace'“

c# - 扩展方法,泛型 List<T> 上的 SumIf

c# - Java中扩展方法的实际用途是什么?

c# - 在插入命令asp中获取ID并在c#后面的代码中使用它

c# - app.config 分离实现

c# - 透明窗口上的wpf webbrowser

vb.net - 扩展方法未被识别