问题描述
我想从传统的JS移动到TypeScript,因为我喜欢C#类似的语法。
我的问题是,我找不到如何在TypeScript中声明静态类。
I wanted to move to TypeScript from traditional JS because I like the C#-like syntax.My problem is that I can't find out how to declare static classes in TypeScript.
在C#中,我经常使用静态类来组织变量和方法,将它们放在一个命名的类中,而不需要安装对象。
在vanilla JS中,我曾经使用一个简单的JS对象:
In C#, I often use static classes to organize variables and methods, putting them together in a named class, without needing to instatiate an object.In vanilla JS, I used to do this with a simple JS object:
var myStaticClass = {
property: 10,
method: function(){}
}
在TypeScript,我宁愿去我的C锐利的方法,但似乎静态类不存在于C#。
这个问题的适当解决方案是什么?
In TypeScript, I would rather go for my C-sharpy approach, but it seems that static classes don't exist in C#. What is the appropriate solution for this problem ?
推荐答案
TypeScript不是C#,所以你不应该期望在TypeScript中的C#的相同概念必然。问题是你为什么想要静态类?
TypeScript is not C#, so you shouldn't expect the same concepts of C# in TypeScript necessarily. The question is why do you want static classes?
在C#中,静态类是一个不能被子类化的类,只能包含静态方法。 C#不允许定义类外的函数。但是,在TypeScript中,这是可能的。
In C# a static class is simply a class that cannot be subclassed and must contain only static methods. C# does not allow one to define functions outside of classes. In TypeScript this is possible, however.
如果你正在寻找一种方法将你的函数/方法放在命名空间TypeScript的模块,例如
If you're looking for a way to put your functions/methods in a namespace (i.e. not global), you could consider using TypeScript's modules, e.g.
module M {
var s = "hello";
export function f() {
return s;
}
}
这样你可以从外部访问Mf
So that you can access M.f() externally, but not s, and you cannot extend the module.
请参阅TypeScript 以获取更多详细信息。
See the TypeScript specification for more details.
这篇关于TypeScript静态类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!