为非常量类型的属性设置 DefaultValue? [英] Setting DefaultValue for properties of non-Constant types?

查看:54
本文介绍了为非常量类型的属性设置 DefaultValue?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Windows.Forms 组件,它有一个返回 Size 结构的mySize"属性.我的目的是让这个属性根据组件的大小自动计算返回的 mySize,除非 mySize 已经明确设置,在这种情况下,返回 mySize 的设置值.不幸的是,现在我将组件嵌入到表单中,Windows 窗体设计器决定开始显式生成和设置 mySize 属性的值,这让我很困惑.

I have a Windows.Forms component which has a "mySize" property that returns a Size struct. My intention was to have this property calculate the returned mySize automatically based on the size of the component, unless mySize has been explicity set, in which case, return the set value of mySize. Unfortunately, now that I am embedding the component into a form, the Windows Forms designer has decided to start explicitly generating and setting a value for the mySize property, which is screwing me right up.

所以我需要设置一个 DefaultValue,这样设计器就会离开而让我一个人呆着.

So I need to set a DefaultValue, so that the Designer will go away and leave me alone.

我已经阅读了有关 System.ComponentModel.DefaultValue 的答案,所以我知道我必须在构造函数中手动设置属性的值,但是我找到的答案和文档只涉及设置 DefaultValue错误,常量.

I've read up on answers dealing with System.ComponentModel.DefaultValue, so I know that I must manually set the value for the property in the constructor, but the answers and documentation I have found only deal with setting a DefaultValue of False, a Constant.

Size 结构不是常量,所以 VB 编译器吓坏了,告诉我我不能将 Size 设置为 Size 类型属性的默认值,因为 Size 不是常量.

A Size struct is not a Constant and so the VB compiler is freaking out, telling me I can't set a Size as the DefaultValue for Property of Type Size because Sizes aren't constants.

这让我的大脑受伤.

我可能可以通过创建 getMySize 和 setMySize 方法而不是使用属性来解决这个问题,但我想知道是否真的有任何方法可以设置 Size 的默认属性.

I can probably code around the problem by making getMySize and setMySize methods instead of using a property, but I'd like to know if there's actually any way to set the default property for a Size.

注意:我没有使用 mySize 作为覆盖 Size 属性的某种疯狂尝试(它的 DefaultValue 为 150x150,因此某些东西似乎能够为 Sizes 设置 DefaultValues);mySize 只是类所需的一些 Size 值.

NB: I'm not using mySize as some kind of deranged attempt to override the Size property (which has a DefaultValue of 150x150, so SOMETHING seems to be able to set DefaultValues for Sizes); mySize is just some Size value required by the Class.

推荐答案

代替应用 DefaultValue 属性,编写以下两个方法:

Instead of applying the DefaultValue attribute, write the following two methods:

bool ShouldSerializemySize() { ... }
void ResetmySize() { ... }

在 ShouldSerializemySize 中,如果值应该序列化为代码,则返回 true.在 ResetmySize 中,将该属性重置为其默认值.

In ShouldSerializemySize, return true if the value should be serialized to code. In ResetmySize, reset the property to its default value.

组件设计器将通过反射自动选择这些方法.

The component designer will automatically pick up these methods via reflection.

更多信息在这里:http://msdn.microsoft.com/en-us/library/53b8022e(VS.71).aspx

这篇关于为非常量类型的属性设置 DefaultValue?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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