我正在尝试在 C# 中为字符串创建自定义扩展,请看下面的示例,我的要求是当字符串无效时,此扩展应返回 DBNull
,否则应返回文本。这个怎么做。
My Factory.IsValidString
具有确定字符串是否有效的所有检查。
public static string DBString(this string Text)
{
return (!Factory.ISValidString(Text)) ? DBNull: Text;
}
最佳答案
正如 Evk 在对您的帖子的评论中所说:
DBNull
andstring
are different types, and they have no common parent type except object, so your extension method should returnobject
and notstring
所以你应该像下面这样重构你的扩展方法:
public static object DBString(this string Text)
{
return (!Factory.ISValidString(Text)) ? (object)DBNull.Value: Text;
}
请记住,您可能需要将返回的对象转换为 string
或 DBNull
,具体取决于使用它的代码正在做什么。
关于c# - 当字符串为 null 时返回 DBnull 的扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50061543/