public class Foo
{
public Foo(){ }
//One of many properties
//set up in the same way
private String _name;
public String Name
{
get { return _name; }
set {
_name = value;
//code that is important to run
//only after the objects initial creation
}
}
private int _id;
public int ID
{
get { return _id; }
set {
_id = value;
//code that is important to run
//only after the objects initial creation
}
}
public void Win()
{
//clean up method that wouldn't be needed
//if I used optional parameters because
//i would be able to set _name (and all the
//other private properties directly without
//using the public Set
}
}
如何在c#
中创建此类对象后自动调用方法Foo ko = new Foo() {
ID = 4,
Name = "Chair"
};
ko.Win(); // <-- Want this to be called automatically inside the class
答案 0 :(得分:2)
在设置一些随机属性集后,没有自动调用的方法(初始化转换为...)
var foo = new Foo { Name = "bar" };
实际上是捷径:
var foo = new Foo();
foo.Name = "bar";
当以第二种形式书写时,我不希望在foo.Name
作业后调用任何神奇的方法。
您可以选择:
set
部分中编写代码。包含构建器模式的代码示例:
var foo = new FooBuilder { Name = "bar" }
.Build();
答案 1 :(得分:0)
将Win()添加到构造函数中。调用/放入构造函数。
public Foo(string value, string value2) {
Value = value;
Value2 = valu2e;
Win();
}
这是构造函数。手动设置。
答案 2 :(得分:0)
好吧,如果你总是设置ID和名称怎么样?
private string _Name;
public string Name
{
get { return _Name; }
set {
_Name = value;
this.Win();
}
}
在您为名称设置值后,将始终调用Win函数,或者您可以为您选择的ID执行此操作!
答案 3 :(得分:0)
不是最具扩展性的解决方案,但为什么不试试这个:
public class Foo
{
public int ID { get; set; }
public String Name { get; set; }
public Foo()
{
}
public Foo( int id )
{
// Win()
ID = id;
// Win()
}
Public Foo( string name )
{
// Win()
Name = name;
// Win()
}
public Foo( int id, string name )
{
// Win()
ID = id;
Name = name;
// Win()
}
public void Win()
{
//Do Stuff that would go into the constructor
//if I wanted to use optional parameters
//but I don't
}
}
您可以在设置属性之前或之后调用Win
。