c#将结构转换为另一个结构 [英] c# Convert struct to another struct

查看:55
本文介绍了c#将结构转换为另一个结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么办法,如何转换它:

Is there any way, how to convert this:

namespace Library
{
    public struct Content
    {
        int a;
        int b;
    }
}

我在Library2.Content中有一个结构,该结构的数据定义方式相同( {int a; int b;} ),但方法不同.

I have struct in Library2.Content that has data defined same way ({ int a; int b; }), but different methods.

是否可以将结构实例从Library.Content转换为Library2.Content?像这样:

Is there a way to convert a struct instance from Library.Content to Library2.Content? Something like:

Library.Content c1 = new Library.Content(10, 11);
Library2.Content c2 = (Libary2.Content)(c1); //this doesn't work

推荐答案

您有几种选择,包括:

  • 您可以定义从一种类型到另一种类型的显式(或隐式)转换运算符.请注意,这意味着一个库(一个定义转换运算符的库)必须依赖于另一个库.
  • 您可以定义自己的实用程序方法(可能是扩展方法),该方法可以将一种类型转换为另一种类型.在这种情况下,执行转换的代码将需要更改以调用实用程序方法,而不是执行强制转换.
  • 您可以只新建一个 Library2.Content ,然后将您的 Library.Content 的值传递给构造函数.
  • You could define an explicit (or implicit) conversion operator from one type to the other. Note that this implies that one library (the one defining the conversion operator) must take a dependency on the other.
  • You could define your own utility method (possibly an extension method) that converts either type to the other. In this case, your code to do the conversion would need to change to invoke the utility method rather than performing a cast.
  • You could just new up a Library2.Content and pass in the values of your Library.Content to the constructor.

这篇关于c#将结构转换为另一个结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆