使用 comboBox.DisplayMember & 是个坏主意吗?ValueMember 属性? [英] Is it a bad idea to use the comboBox.DisplayMember & ValueMember properties?

查看:22
本文介绍了使用 comboBox.DisplayMember & 是个坏主意吗?ValueMember 属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在向 WinForms 应用程序添加组合框,我遇到了 DisplayMember &ValueMember 属性.它们的功能正是我在应用程序中所需要的,但我不确定我是否喜欢它们的工作方式.

I'm adding a combobox to a WinForms application, I came across the DisplayMember & ValueMember properties. Their functionality is exactly what I need in my application, but I'm not sure I like the way they work.

comboBox.Items.Add(myObj);
comboBox.DisplayMember = "Name";
comboBox.ValueMember = "Id";

在上面的代码中,我的对象是实际的项目",它的名称是 &Id 属性将用于显示的文本 &分别选定的值.我不确定的是硬编码的名称"&Id"被传递到这些属性中.这是在编译时没有检查的东西.因此,如果我将 object.Name 属性更改为 object.FullName,此代码将在运行时中断.

In the code above my object is the actual "Item", and it's name & Id properties will be used for displayed text & selected value respectively. The thing I'm unsure of is the hard coded "Name" & "Id" being passed into those properties. That is something not checked at compile time. So, if I ever changed my object.Name property to object.FullName, this code would break at runtime.

我考虑过动态获取属性名称(如此处所问:获取变量或参数的名称),但感觉很不对.

I've thought about getting the property name dynamically (as asked here: get name of a variable or parameter), but that feels very wrong.

那么,使用这些属性是否不明智?如果是这样,将我的对象存储为组合框项目的推荐方法是什么?

So, is it ill-advised to use these properties? If so, what is the recommended way to store my object as the combobox item?

推荐答案

使用它们非常好.

关于编译时检查的问题:在 C# 的下一个版本中,有一个 nameof 运算符,与现在已经存在的 typeof 相当.

For your concern of compile-time checks: in the next version of C# there is a nameof operator, comparable to the typeof there is now already.

你可以这样使用它:

comboBox.DisplayMember = nameof(obj.Name);

解决方案已经在那里得到类似的结果.

There are solutions already there to get a similar result.

这篇关于使用 comboBox.DisplayMember & 是个坏主意吗?ValueMember 属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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