C# 为什么要编写符合 CLS 的代码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1828575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 21:11:43  来源:igfitidea点击:

Why should I write CLS compliant code?

c#cls-compliant

提问by Luca

I've found a lot of pages about CLS compliance.

我找到了很多关于 CLS 合规性的页面。

I've understood that CLS compliance:

我了解 CLS 合规性:

Many peolple write that "if you write code, you should write it CLS compliant." But as far I can read, there is no reason to use CLS compliance in generic software.

许多人写道“如果你编写代码,你应该编写符合 CLS 的代码”。但据我所知,没有理由在通用软件中使用 CLS 合规性。

Am I right, or did I miss something?

我是对的,还是我错过了什么?

采纳答案by Remus Rusanu

If you write a library or framework it makes sense to ensure your library can be used from any CLR language.

如果您编写一个库或框架,确保您的库可以从任何 CLR 语言中使用是有意义的。

回答by Adam Robinson

There may not be a specificreason to have your code be CLS compliant, but people are referring to it being a "best practice"--something that you should do because it's a good habit, rather than being measurably better for a particular scenario.

可能没有特定的理由让您的代码符合 CLS,但人们将其称为“最佳实践”——您应该这样做,因为这是一个好习惯,而不是在特定情况下明显更好。

In other words, it's a good ideato make your code CLS compliant unless you have a reason notto.

换句话说,除非您有理由不这样做,否则最好使您的代码符合 CLS 。

回答by plinth

The answer is to allow maximum compatibility across .NET languages. CLS is the lingua francathat allows C# assemblies to work with F#, Iron Python, C++/CLI, VB.NET, Boo and all the other .NET languages. Step outside that boundary and your assembly may work correctly, but not necessarily.

答案是允许跨 .NET 语言的最大兼容性。CLS 是通用语言,它允许 C# 程序集与 F#、Iron Python、C++/CLI、VB.NET、Boo 和所有其他 .NET 语言一起使用。走出该边界,您的程序集可能会正常工作,但不一定。

回答by Dathan

CLS-compliance is particularly important if you're distributing libraries - specifically, writing CLS compliant guarantees that your libraries will be usable by all CLS-compliant languages.

如果您要分发库,则 CLS 合规性尤其重要——特别是,编写 CLS 合规性保证您的库可被所有 CLS 合规语言使用。

For instance, Visual Basic is not case-sensitive, whereas C# is. One of the requirements of CLS compliance is that public (and protected) member names should not differ only by case, thus ensuring that your libraries can be used safely by Visual Basic code, or any other .NET language that doesn't differentiate based on case.

例如,Visual Basic 不区分大小写,而 C# 是。CLS 合规性的要求之一是公共(和受保护的)成员名称不应仅因大小写而异,从而确保 Visual Basic 代码或任何其他不区分大小写的 .NET 语言可以安全地使用您的库案件。