Publisher无法转换为字符串

本文关键字:字符串 转换 Publisher | 更新日期: 2023-09-27 18:24:59

如何将字符串转换为标签。

string str = "Test String";
object objString = (object)str;
Label lbl = (Label)objString; //InvalidCastException was unhandled
lbl.BackColor = Color.Red;
lbl.ForeColor = Color.Red;

Publisher无法转换为字符串

String不是Label。。(无法将String转换为Label

试试这个:

string str = "Test String";
Label lbl = new Label() { Text = str }; 
lbl.BackColor = Color.Red;
lbl.ForeColor = Color.Red;

实际上,您可以将字符串转换为标签,只需一些技巧

public class myLabel:Label
{
  public static explicit operator myLabel(string text)
   {
     myLabel lbl = new myLabel();
     lbl.Text = text;
     return lbl;
   }
}

然后在你的演示中

    myLabel lbl = new myLabel();
    lbl = (myLabel)"abc1234";
    form1.Controls.Add(lbl);