C#泛型约束,包括价值类型和字符串 [英] C# Generic constraints to include value types AND strings

查看:845
本文介绍了C#泛型约束,包括价值类型和字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着写IEnumerable的扩展方法,将只适用于值类型和字符串。

I'm trying to write an extension method on IEnumerable that will only apply to value types and strings.

public static string MyMethod<T>(this IEnumerable<T> source) where T : struct, string

然而字符串'不是一个有效的约束,因为它是一个密封类。

However 'string' is not a valid constraint as it is a sealed class.

有没有办法做到这一点?

Is there any way to do this?

编辑:

什么实际上,我试图做的是在一个动态构建的IN的条款准备值的列表。SQL

What I'm actually trying to do is prepare a list of values for an "IN" clause in a dynamically constructed SQL.

我有很多的代码实例,例如,我要清理以下内容:

I have lots of instances of code such as the following that I want to clean up:

sb.AppendLine(string.Format("AND value IN ({0})", string.Join(",", Values.Select(x => x.ToSQL()).ToArray())));



在哪里ToSQL()的代码来处理SQL注入攻击。

Where ToSQL() has code to handle SqlInjection.

推荐答案

没有,你不能。通用约束总是与-ed分词,如果你明白我的意思(即所有的约束必须是satisifed),所以即使你试图使用一些非密封类,这仍然会失败。

No, you can't. Generic constraints are always "AND"-ed, if you see what I mean (i.e. all constraints must be satisifed), so even if you were trying to use some unsealed class, this would still fail.

你为什么要这么做?或许还有另一种方法,它能够更好地工作。

Why do you want to do this? Perhaps there's another approach which would work better.

这篇关于C#泛型约束,包括价值类型和字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆