Ste*_*eve 6 c# default properties
问题1:
我有一个简单的winforms应用程序,我希望DataBind我的Person.Name属性到一个文本框.名称的类型为StringField.我最初将Name属性定义为String.数据绑定在值类型(如String)上非常有用.我希望StringField.Value属性是StringField的默认属性.我想在textBox中看到StringField.Value的值而不是文本"FieldApp.StringField".
问题2:
我希望能够使用operator =将字符串分配给StringField.此赋值将导致设置StringField.Value成员.
这可以实现吗?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace FieldApp
{
public class StringField
{
public string Value { get; set; }
}
public class Person
{
//private String _Name;
//public String Name
//{
// get { return _Name; }
// set { _Name = value; }
//}
//public Person(string name)
//{
// Name = name;
//}
private StringField _Name;
public StringField Name
{
get { return _Name; }
set { _Name = value; }
}
public Person(string name)
{
Name = new StringField();
Name.Value = name;
}
}
public partial class FieldAppForm : Form
{
Person person = new Person("steve");
public FieldAppForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//our form contains a button1 and textBox1
//this compiles
person.Name.Value = "steve";
//this does not. Is there anyway to accomplish this?
person.Name = "steve";
//steve appears in the textbox
textBox1.DataBindings.Add("Text", person, "Name.Value");
//FieldApp.StringField appears in the textbox
textBox1.DataBindings.Add("Text", person, "Name");
}
}
}
Run Code Online (Sandbox Code Playgroud)
Øyv*_*aar 10
您可以创建一个implisit运算符重载.然后你可以从这样的字符串创建Stringfield:
StringField field = "value of new object";
string value=(string)field;
Run Code Online (Sandbox Code Playgroud)
知道这会创建一个新的StringField对象.我不会建议你这样做.
[System.Diagnostics.DebuggerDisplay("{Value}")]
public class StringField
{
public string Value { get; set; }
public static implicit operator StringField(string s)
{
return new StringField { Value = s };
}
public static explicit operator string(StringField f)
{
return f.Value;
}
public override string ToString()
{
return Value;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16994 次 |
| 最近记录: |