[英]Generic return type and non-nullable objects
I have a Sql Utility class which contains a lot of handy methods around Sql queries. 我有一个Sql Utility类,其中包含许多有关Sql查询的便捷方法。 This class contains the following method:
此类包含以下方法:
public static T ExecuteScalar<T>(
string query,
SqlConnection connection,
params SqlParameter[] parameters)
where T : class, new()
{
SqlCommand command =
CreateCommand(query, connection, parameters);
return command.ExecuteScalar() as T;
}
Is it possible to return for example Guid
objects or other non-nullable classes. 是否可以返回例如
Guid
对象或其他非空类。
Something like this: 像这样:
Guid result =
SqlUtils.ExecuteScalar<Guid>(
@"SELECT [Id] FROM [dbo].[MyTable]
WHERE [Column1] = @Param1",
connection,
new SqlParameter("@Param1", "someValue"));
You can use default(T)
(and you should remove the generic type constraints): 您可以使用
default(T)
(并且应该删除通用类型约束):
SqlCommand command =
CreateCommand(query, connection, parameters);
object value = command.ExecuteScalar();
if (value == null || value is DbNull)
{
return default(T)'
}
return (T)value;
Not the way you've written it. 不是您编写的方式。 The
as
operator may return null
if the cast fails, therefore T
has to be of a reference type. 如果强制转换失败,则
as
运算符可能返回null
,因此T
必须是引用类型。
For value types, you'll need to use a conventional cast operator (T)
. 对于值类型,您需要使用常规的强制转换运算符
(T)
。 You'll also need to remove the constraint that T
is a reference type on the method definition. 您还需要删除方法定义中
T
是引用类型的约束。
public static T ExecuteScalar<T>(string query,
SqlConnection connection,
params SqlParameter[] parameters)
{
SqlCommand command = CreateCommand(query, connection, parameters);
var result = command.ExecuteScalar();
if (result is T) return (T)result;
return default(T);
}
Because the constraints of this method return a class type, you'd be able to return any object that match a class type (non-primitive). 由于此方法的约束返回类类型,因此您可以返回与类类型匹配的任何对象(非基本类型)。 Given the nature of your method though, I don't see any need for the constraint.
鉴于您的方法的性质,我认为不需要任何约束。 You should be able to remove this constraint and return any type that you can generate.
您应该能够删除此约束并返回可以生成的任何类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.