C#如何从派生类ToolStripMenuItem检索自定义属性值 [英] C# How to retrieve custom property value from derived class ToolStripMenuItem

查看:81
本文介绍了C#如何从派生类ToolStripMenuItem检索自定义属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

3天后我一直在寻找这个看似简单的问题的答案。 

For 3 days now I've been searching the answer to this seemingly easy question. 

我创建了一个这样的类:

I've created a class like so:

公共类SourceMenuItem:ToolStripMenuItem

public class SourceMenuItem : ToolStripMenuItem

{

private字符串连接;

private string connection;

公共字符串Conn

            {

               得到
                {

                   返回连接;

                }


               设为

                {

                    connection = value;

                }¥b $ b            }

public string Conn
            {
                get
                {
                    return connection;
                }

                set
                {
                    connection = value;
                }
            }

}

我的ToolStripMenuItem控件名为SourceLeft System.Windows.Forms.ToolStripMenuItem

My ToolStripMenuItem control is called SourceLeft System.Windows.Forms.ToolStripMenuItem

以下是我动态添加项目的方法

SourceMenuItem item = new SourceMenuItem();

SourceMenuItem item = new SourceMenuItem();

item.Text =" drive c:" ;;

item.Text = "drive c:";

item.Tag =" drive"; 

item.Tag = "drive"; 

item.Conn =" my string to retrieve";

item.Conn = "my string to retrieve";

//(其他东西像ToolTipText等...)

// (other stuff like ToolTipText, etc...)

SourceLeft.DropDownItems.Add(item);

SourceLeft.DropDownItems.Add(item);

以下是我检索值的方法

string text ="" ;;

string text = "";

string tag ="" ;;

string tag = "";

string conn ="" ;;

string conn = "";

int max = SourceLeft.DropDownItems.Count;                     

int max = SourceLeft.DropDownItems.Count;                    

 

预期会出现.Conn的错误消息:

The error message for .Conn is to be expected:

ToolStripItem不包含'Conn的定义'并且没有可访问的扩展方法'Conn'可以找到'ToolStripItem'类型的第一个参数。

ToolStripItem does not contain a definition for 'Conn' and no accessible extension method 'Conn' accepting a first argument of type 'ToolStripItem' could be found.

我是C#的新手并且无法找到关于我缺少的代码的答案:&bbsp;

I'm new to C# and couldn't find the answer about the code I'm missing to make this work: 

我希望以与.Text& ;;相同的方式处理.Conn属性。 .Tag 

I wish to address the .Conn property the same way I do with .Text & .Tag 

感谢您的帮助

祝您有愉快的一天。




推荐答案

试试这个:

    conn =(SourceLeft.DropDownItems [i] as SourceMenuItem)?。Conn;

   conn = (SourceLeft.DropDownItems[i] as SourceMenuItem)?.Conn;

If此菜单项不同,则 conn 将为空。

If this menu item is different, then conn will be null.

您还可以指定多个自定义 ToolStripMenuItem 的数据(类)到
标记
属性。然后,您不必创建派生项。只需投放
标记对象。

You can also assign multiple custom data (a class) to Tag property of ToolStripMenuItem. Then you do not have to create derived items. Just cast the Tag object.


这篇关于C#如何从派生类ToolStripMenuItem检索自定义属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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