简体   繁体   English

文本框文本作为对象的名称

[英]Textbox text as Object's name

I have a TextBox named "tb1" (Not real name). 我有一个名为“ tb1”的TextBox(不是真实名称)。

I want to, when I click a button; 我想要,当我单击一个按钮时; create an "Product" object with the value of the "tb1" text. 用“ tb1”文本的值创建一个“产品”对象。

Something like... 就像是...

Product tb1.text = new Product();

How do I do it ? 我该怎么做 ?

You need to override the constructor on the Product object so that it can accept a string parameter. 您需要重写Product对象上的构造函数,以便它可以接受字符串参数。

Product object : 产品对象

public Product(string productName)
{
    //set product name variable using productName parameter
    _productName = productName;   
}

And then you can do something like this: 然后您可以执行以下操作:

//set product name using new constructor
Product product = new Product(tb1.Text);

使用new关键字创建时,将“ tb1.text”传递给Product的构造函数。

Your example is trying to create a Product where the variable name is the content of tb1.Text. 您的示例试图创建一个产品,其中变量名是tb1.Text的内容。 Far as I know, thats impossible. 据我所知,那是不可能的。 It'd be really confusing for anybody reading the code later anyway, so even if it is possible please don't do it. 对于以后无论如何阅读代码的人来说,这真的很令人困惑,因此即使有可能也请不要这样做。 :) :)

If you're just trying to create a Product where the Product name is set to the value of tb1.Text, you can do this: 如果您只是尝试创建一个产品,其中产品名称设置为tb1.Text的值,则可以执行以下操作:

Product someProduct = new Product();
someProduct.Name = tb1.Text;

Or pass into the constructor like Arun mentioned. 或传递给Arun提到的构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM