在打字稿中,我可以将类型定义为字符串或像这样的字符串数组
type MyStringType = string | string[]
我可以在C#中做类似的事情吗?
答案 0 :(得分:1)
不,你不能。 C#是一种强类型语言,不会 (还)允许变量的声明为多种类型。
可以选择使用dynamic
关键字:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/using-type-dynamic
类型是静态类型,但是动态类型的对象会绕过静态类型检查。在大多数情况下,它的功能就像具有类型对象。在编译时,假定类型为动态的元素支持任何操作。因此,您不必担心对象是从COM API,从动态语言(如IronPython),从HTML文档对象模型(DOM),从反射还是从程序中的其他地方获取其值。但是,如果代码不是vali
有效地,它可以用作打字稿中的any
类型,但由于可能会出现运行时错误,因此不建议使用它。
答案 1 :(得分:1)
C#不具有联合类型的功能。有proposals个,但我认为它们不会很快被计划。
话虽如此,您可以实现自定义包装器类型,并在使用输入之前将其转换为该类型。
<template>
<tiptap model="editNoteContent" extensions" />
</template>
<script>
export default {
computed: {
editNoteContent: {
get() {
return this.$store.state.Notes.currentNote.text;
},
set(text) {
this.$store.commit("Notes/updateCurrentNoteText", text);
},
}
},
}
</script>
由于隐式转换,您可以使用需要结合的任何变体的值。所以这两项工作:
struct Union<T1, T2>
{
public T1 Left { get; }
public T2 Right { get; }
public bool IsLeft => !IsRight;
public bool IsRight { get; }
public Union(T1 left) => (Left, Right, IsRight) = (left, default, false);
public Union(T2 right) => (Left, Right, IsRight) = (default, right, true);
public static implicit operator Union<T1, T2>(T1 left) => new Union<T1, T2>(left);
public static implicit operator Union<T1, T2>(T2 right) => new Union<T1, T2>(right);
}
请注意,这不是生产级的实现。您可能想覆盖void Foo(Union<string, string[]> val){}
Foo("str")
Foo(new string[] {"str1", "str2"});
,如果某人在Equals
为InvalidOperarionException
时访问Left
,则可能抛出IsLeft
,反之亦然。
实际的语言支持的实现将具有较少的开销(可能重复使用大小为false
的单个字段,但可惜的是,此Works™且类型强。