C#添加隐式的转换现有的类型

C#添加隐式的转换现有的类型

本文介绍了C#添加隐式的转换现有的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有在C#的方式来添加的转换到其他组件已定义的类型?

Is there a way in C# to add implicit conversions to types already defined in other assemblies?

例如,如果我使用两种不同的组件,每个提供自己的的Vector3结构,并在它们的API使用它,这将是很好能够一次定义转换,然后只需通过一个 Foo.Vector3 来的方法期望一个 Bar.Vector3 ,并将它的自动转换

For example, if I am using two different assemblies which each provide their own Vector3 struct, and use it in their APIs, it would be nice to be able to define a conversion once, and then just pass a Foo.Vector3 to a method that expects a Bar.Vector3, and have it automatically converted.

如果我有源库,然后我可以添加隐式转换运营商。如果没有这些来源,我目前在做转换明确自己与助手功能,每一次。我希望有一个更好的方式。

If I had the source for the libraries then I could add implicit conversion operators. Without that source, I am currently doing the conversion explicitly myself with a helper function every time. I'm hoping for a nicer way.

我知道我可以创建自己的的Vector3结构隐式转换操作符并从其他两个结构,但是这不会解决所有我想要去的直接的传递一个(外部定义)的对象的情况下,键入希望其他的方法。

I realize I could create my own Vector3 struct with implicit conversion operators to and from the other two structs, but this wouldn't solve all the cases where I want to directly pass an object of one (externally defined) type to a method expecting the other.

奖金问题:有,揭露事情像他们的API中的Vector3结构应该做的,方便的易用性在这方面图书馆的任何作家

Bonus question: is there anything authors of libraries that expose things like a Vector3 struct in their API should do to facilitate ease of use in this regard?

推荐答案

您可以提供隐式转换到和来自第三方类型的任何类型的您创作自己,但是你不能添加对于两个第三方类型之间的隐式转换的支持

You can provide implicit conversion to-and-from a third-party type for any type that you author yourself, but you cannot add support for implicit conversion between two third-party types.

您可以稍微加扩展方法,这两种的Vector3类型的改善两种类型之间转换的风采;

You could improve the elegance of converting between the two types somewhat by adding extension methods to both Vector3 types;

public static Bar.Vector3 ToBarVector3(this Foo.Vector3 foo) {
    return /* instance of Bar.Vector3 */
}

public static Foo.Vector3 ToFooVector3(this Bar.Vector3 bar) {
    return /* instance of Foo.Vector3 */
}

这是关于你可以期望达到最佳状态。

That's about the best you can expect to achieve.

这篇关于C#添加隐式的转换现有的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:44