【问题标题】:MarshalAs for Properties in a structMarshalAs 用于结构中的属性
【发布时间】:2021-10-05 02:42:35
【问题描述】:

我正在尝试将 getter 和 setter 添加到此结构中,因此我可以将其用作 listView 项目源。问题是,这会导致 MarshalAs 无效,因此不允许编译。解决此问题的最佳选择是什么?

属性“MarshalAs”在此声明类型上无效。它仅对“字段、参数、返回”声明有效。**

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public struct FileExplorerData
    {
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 251)]
        public string name { get; set; }
        public FILETIME lastwrite { get; set; }
        public bool type { get; set; }
        public int size { get; set; }
    };

【问题讨论】:

  • 简单 - MarshalAs 不能用于 property
  • 是的@T.S.,这正是问题所在。您有可以推荐的解决方案吗?
  • [System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.ReturnValue, Inherited=false)] -- 这是你的解决方案
  • 但是为什么你需要这个数据源呢?这是winforms还是WPF?
  • @T.S.我有一个这些结构的列表,我将其设置为 WPF 列表视图的数据源。

标签: c# .net wpf


【解决方案1】:

你可以指定底层字段作为属性的目标

[field: MarshalAs(UnmanagedType.ByValTStr, SizeConst = 251)]
public string name { get; set; }

这从 C# 7.3+ 开始有效。见the documentation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 2011-07-04
    相关资源
    最近更新 更多