gpt4 book ai didi

c# - 在 C#/VB 中使用 Windows API 结构的 Ansi 和 Unicode 版本的简单方法

转载 作者:行者123 更新时间:2023-11-30 21:49:08 29 4
gpt4 key购买 nike

出于互操作的原因,我需要同时使用某些 Windows API 结构的 ANSI 和 Unicode 版本 (DEVMODE)。

有没有办法不用两次声明所有内容?目前,我的结构定义如下:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
struct DevModeAnsi
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string dmDeviceName;
public Int16 dmSpecVersion;
// ... lots of other fields ...
public Int16 dmOrientation;
// ... lots of other fields ...
}

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct DevModeUnicode
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string dmDeviceName;
public Int16 dmSpecVersion;
// ... lots of other fields ...
public Int16 dmOrientation;
// ... lots of other fields ...
}

更糟糕的是,我还需要复制所有代码:

bool IsLandscapeOrientation(DevModeAnsi d) { return d.dmOrientation == DMORIENT_LANDSCAPE; }
bool IsLandscapeOrientation(DevModeUnicode d) { return d.dmOrientation == DMORIENT_LANDSCAPE; }

我考虑过以下解决方案:

  • 建立一个通用的基础结构:行不通,因为结构不支持继承。

  • 使用通用接口(interface):行不通,因为接口(interface)不能包含字段,只能包含属性。因此,我必须为我想要访问的每个字段创建一个属性,将字段列表四倍而不是简单地加倍。

    <
  • T4:不得已,但如果可能的话,我宁愿避免那种额外的复杂性。

是否有我错过的优雅解决方案?

最佳答案

Is there a way to do that without declaring everything twice?

没有。

Is there an elegant solution that I've missed?

没有。

您可以编写自己的编码代码来序列化此类结构,并增加您想要的灵 active 。但所付出的努力将远远超过 yield 。

关于c# - 在 C#/VB 中使用 Windows API 结构的 Ansi 和 Unicode 版本的简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37185794/

29 4 2
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com