如何以编程方式构造对象引用? [英] How can I programmatically construct the object reference?

查看:23
本文介绍了如何以编程方式构造对象引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有三个文本框:TextBox1、TextBox2、TextBox3.通常,如果我想更改文本,例如我会放置 TextBox1.Text = "Whatever" 等等.对于我现在正在做的事情,我想要一些类似 (TextBox & "i").Text 的内容.这显然不是我需要使用的语法,我只是将它用作我需要做的事情的示例.那么我该怎么做呢?我这样做的主要原因是通过循环减少代码.

Lets just say that I have three textboxes: TextBox1, TextBox2, TextBox3. Normally if I wanted to change the text for example I would put TextBox1.Text = "Whatever" and so on. For what I'm doing right now I would like to something like (TextBox & "i").Text. That obviously isn't the syntax I need to use I'm just using it as an example for what I need to do. So how can I do something like this? The main reason I'm doing this is to reduce code with a loop.

请记住,我实际上并没有更改文本框的文本,我只是将其用作示例来说明问题.

Please keep in mind that I'm not actually changing the text of the textboxes I'm simply using that as an example to get the point across.

推荐答案

当您动态创建 TextBox 时,您可以使用更容易的 TextBox 数组.
但是也可以使用反射:

When you create your TextBox dynamically you can use an array of TextBoxes which is much easier.
However it is possible to use reflection, too:

var textBoxes = GetType().GetFields( BindingFlags.NonPublic | BindingFlags.Instance )
foreach( var fieldInfo in textBoxes )
{
    if( fieldInfo.FieldType == typeof( TextBox ) )
    {
        var textBox = ( TextBox )fieldInfo.GetValue( this );
        textBox.Text = "";
    }
}

这篇关于如何以编程方式构造对象引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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