网站首页 全球最实用的IT互联网站!

人工智能P2P分享Wind搜索发布信息网站地图标签大全

当前位置:诺佳网 > 软件工程 > 后端开发 > .Net >

C# 如何在 PropertyGrid 中,对同一double的成员显示出

时间:2024-12-03 11:38

人气:

作者:admin

标签:

导读:这段时间搞东西,接触到这个,整了好几天。终于 Stackoverflow 上找到一个与我思路上一样的答案。之前用了好多遍 百度 AI 的方法都牛头不对马嘴。 看来 自己对 这一套 C# 的中的反射机...

这段时间搞东西,接触到这个,整了好几天。终于 Stackoverflow 上找到一个与我思路上一样的答案。之前用了好多遍 百度 AI 的方法都牛头不对马嘴。

看来 自己对 这一套 C# 的中的反射机制中的内容还不是太熟悉。所以摸了好久。

主要思路是这样的:

PropertyGrid 可以把一个对象中 public 成员 都显示到界面上去,供使用者修改,如下:

这个对象的类是这样的:

1 public class testObject
2 {
3     [TypeConverter(typeof(CustomDoubleConverter)), PrecisonAttribute(3), Category("all"), Description("this is a double 1")]
4     public double MyDouble1 { get; set; }
5 
6     [TypeConverter(typeof(CustomDoubleConverter)), PrecisonAttribute(2), Category("all"), Description("this is a double 2")]
7     public double MyDouble2 { get; set; }
8 }

在主程序里是这样把这个 对象 与 PropertyGrid 关联起来的:

public Form1()
{
   testObject to = new testObject();
InitializeComponent(); to.MyDouble1
= 1.2222f; to.MyDouble2 = 2.1f; propertyGrid1.SelectedObject = to; }

显示出来是这样的:

可以看到,通过指定不同值的 PrecisonAttribute,让两个都是 double 的值,在 PropertyGrid 里显示出不同长度的小数点后长度值。

上面 testObject 里,两个 double 成员,都指定了 自定义的 typeConverter 的类 CustomDoubleConverter,如下:

public class CustomDoubleConverter : DoubleConverter
{

    public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
    {
        if (destinationType == typeof(string) && value is double doubleValue)
        {
            int d = 0;

            if ( context != null )
            {
                AttributeCollection ac = context.PropertyDescriptor.Attributes;

                PrecisonAttribute pa = (PrecisonAttribute)ac[typeof(PrecisonAttribute)];
                if (pa != null)
                    d = pa.Precison;
            }

            return doubleValue.ToString("N" + d, culture);
        }
        return base.ConvertTo(context, culture, value, destinationType);
    }
}

public class PrecisonAttribute : Attribute
{
    // The constructor is called when the attribute is set.
    public PrecisonAttribute(int value)
    {
        _precison = value;
    }

    // Keep a variable internally ...
    protected int _precison;

    // .. and show a copy to the outside world.
    public int Precison
    {
        get { return _precison; }
        set { _precison = value; }
    }
}

以上这段代码里:

AttributeCollection ac = context.PropertyDescriptor.Attributes;

PrecisonAttribute pa = (PrecisonAttribute)ac[typeof(PrecisonAttribute)];

这两句就是本文精华。之前整了好久,都找不到如何在这里获得传入的其它元数据的。主要还是自己对 TypeConverter 结构 以及 反射机制不是很熟悉。所以也没仔细去看 context 这个参数。现在想想应该还是蛮合理的:上下文。

温馨提示:以上内容整理于网络,仅供参考,如果对您有帮助,留下您的阅读感言吧!
相关阅读
本类排行
相关标签
本类推荐

CPU | 内存 | 硬盘 | 显卡 | 显示器 | 主板 | 电源 | 键鼠 | 网站地图

Copyright © 2025-2035 诺佳网 版权所有 备案号:赣ICP备2025066733号
本站资料均来源互联网收集整理,作品版权归作者所有,如果侵犯了您的版权,请跟我们联系。

关注微信