C#记录可以自动转换为不太具体的类型,就像在TypeScript中一样。

huangapple go评论65阅读模式
英文:

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);
	}
}

huangapple
  • 本文由 发表于 2023年4月19日 22:11:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76055539.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定