英文:
C# record auto castable to less specific, like in TypeScript
问题
我正在尝试实现一些在 TypeScript 中非常容易的事情,以至于我甚至不会考虑它。我想要像 Tuple 一样,具有命名的类型属性,但我希望它能够与不太具体的版本自动兼容。
在 TypeScript 中:
{
A: string,
B: boolean
}
可以传递给 function(x: {B: boolean})
或函数 function(x: {A: string})
而不会出现任何问题。如何实现这一点?
我一直在考虑 Tuple、Record、Interfaces、Classes,但没有什么特别合适的方法。
英文:
I am trying to achieve something which in TypeScript is so easy that I do not even think about it. I want something like Tuple, with namned typed properties, but I want it to be auto-compatible with less specific versions.
In Typescript:
{
A: string,
B: boolean
}
can be passed into function(x: {B: boolean})
or the function function(x: {A: string})
without any problems. How can this be done?
I have been thinking of Tuple, Record, Interfaces, Classes but nothing has really stuck.
答案1
得分: 1
Unfortunately, C# is strongly typed language, so it won't be that easy as in TypeScript. The thing you want to try to achieve (which is OOP abstraction) is usually done with interfaces and base classes in C#.
For your example it could be following
public interface IInterfaceA
{
string A {get; set;}
}
public interface IInterfaceB
{
bool B {get; set;}
}
public class MyClass: IInterfaceA, IInterfaceB
{
public string A {get; set;}
public bool B {get; set;}
}
public class Program
{
public static void Function1(IInterfaceA input)
{
Console.WriteLine(input.A);
}
public static void Function2(IInterfaceB input)
{
Console.WriteLine(input.B);
}
public static void Main()
{
var myClass = new MyClass() { A = "value", B = true };
Function1(myClass);
Function2(myClass);
}
}
英文:
Unfortunately, C# is strongly typed language, so it won't be that easy as in TypeScript. The thing you want try to achieve (which is OOP abstraction) is usually done with interfaces and base classes in C#.
For your example it could be following
public interface IInterfaceA
{
string A {get; set;}
}
public interface IInterfaceB
{
bool B {get; set;}
}
public class MyClass: IInterfaceA, IInterfaceB
{
public string A {get; set;}
public bool B {get; set;}
}
public class Program
{
public static void Function1(IInterfaceA input)
{
Console.WriteLine(input.A);
}
public static void Function2(IInterfaceB input)
{
Console.WriteLine(input.B);
}
public static void Main()
{
var myClass = new MyClass() { A = "value", B = true };
Function1(myClass);
Function2(myClass);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论