c# - 修复用户控件属性的 .NET 代码生成

标签 c# .net visual-studio winforms user-controls

我有一个 IEnumerable<SomeClassIWrote> 类型的属性在用户控件中。当我在 GUI 中使用此控件时,.Designer.cs 文件包含以下行:

theObject.TheProperty = new SomeClassIWrote[0];

由于某种原因导致编译器警告:

Object of type 'SomeClassIWrote[]' cannot be converted to type
'System.Collections.Generic.IEnumerable`1[SomeClassIWrote]'.

这对我来说是一个谜,因为我一直将数组作为 IEnumerables 传递,并且编译器从未提示过。

就其值(value)而言,我为该属性指定了默认值 null,但在设置默认值之前我遇到了相同的错误。

如何解决此问题,以便 Visual Studio 不会提示并在每次打开设计器时要求我忽略并继续?


属性代码:

[DefaultValue(null)]
public IEnumerable<SomeClassIWrote> TheProperty {
    get { 
        return _theProperty; 
    }
    set {
        if (value == null) {
            _theProperty = new SomeClassIWrote[] { };
        }
        else {
            _theProperty = value;
        }
    }
}

最佳答案

首先,您希望能够在设计器中设置它吗?

如果没有,请添加以下属性:

    [Browsable(false)]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]

如果您确实想在设计器中进行设置,我首先将您的类尝试为 SomeClassIWrote[],看看是否有效。

除此之外,这里使用 IEnumerable 有那么重要吗?正如您所说,您可以将数组作为 IEnumerable 传递。

我怀疑设计器内部可能存在一些限制,比我聪明的人都知道......

如果您确实想要 IEnumerable 属性,则可以将数组公开为 IEnumerable,但将数组保留为设计人员友好的支持字段。

关于c# - 修复用户控件属性的 .NET 代码生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1860096/

相关文章:

c# - XML 将列表对象序列化为从 XSD 文件生成的 XmlText (XmlTextAttribute)

javascript - 从 ASP.NET MVC 中的 AngularJS Controller 加载数据,无需加载整个页面

c# - Blazor Server Scoped 在刷新页面时再次初始化

c# - C# 中的共享对象用于 python 脚本

c# - Visual Studio T4 与 CodeSmith

c# - ORA-01000 : maximum open cursors exceeded using oracle instant client and C#

c# - 如何通过 MSBuild 为 Windows 服务和 Windows 应用程序创建基于文件的简单分发

c# - .Net 桌面应用程序和 Web 应用程序之间的技术区别是什么?

c# - 在c#中单击按钮时显示包含sql数据的消息框

c++ - arduino 和 Visual Studio C++,2 路串行通信