好的,这是我正在尝试解决的问题 - 我想通过linq从db返回返回的对象特性到此对象属性,并且可以更新任何更改,而无需在db中插入新行.
partial class Employee : Person
{
public Employee(int id = 0)
{
if (id > 0)
this.get(id);
}
public override bool get(int id)
{
Employee empl = db.Employees.Single(Employee => Employee.id == id);
if (empl != null)
{
// here I need to do sth like
this = empl;
// or
ObjectProperties.Copy(empl, this);
return true;
}
else
return false;
}
public override void save()
{
if (this.id > 0)
{
db.SubmitChanges();
}
else
{
db.Employees.InsertOnSubmit(this);
db.SubmitChanges();
}
}
public override void remove()
{
if (this.id > 0)
{
db.Employees.DeleteOnSubmit(this);
db.SubmitChanges();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我不想让get方法静态.
由于我们没有太多关于您的应用程序或最终目标使用情况的背景,因此很难为您提供一个很好的示例/建议.但是,在struct发布的方案之外,您无法重新分配this参考.根据您的使用/应用,它可能是可能的,或者更正确使用ref关键字,但我不知道在那个没有关于您的使用情况的详细信息.
但是根据您的评论,您只想更新类的所有属性,最简单的方法是使用一种"CopyInfo"方法,该方法只会复制另一个实例的值:
class MyClass
{
public MyClass()
{
this.id = 2;
}
public void get()
{
CopyInfo(NewClass.Create());
}
private void CopyInfo(MyClass otherInstance)
{
this.id = otherInstance.id;
}
}
Run Code Online (Sandbox Code Playgroud)
另一种选择可能是将各种属性提取到接口,然后您可以围绕类的可重新分配的实例创建一种包装器:
public interface MyInterface
{
public int id { get; }
}
class MyClass : MyInterface
{
public int id { get; private set; }
public MyClass()
{
id = 2;
}
}
Run Code Online (Sandbox Code Playgroud)
然后包装类可能是:
class MyReassignableClass : MyInterface
{
private MyClass BackingInstance;
public int id
{
get
{
return BackingInstance.id;
}
}
public void get()
{
BackingInstance = NewClass.create();
}
}
Run Code Online (Sandbox Code Playgroud)
您的代码可以像对待它一样对待它MyInterface,但访问其成员实际上是间接访问可以根据需要换出的另一个实例的成员.
编辑:最后,我还建议你看看C#命名指南,以确保你的代码与大多数C#.NET代码更加一致.
| 归档时间: |
|
| 查看次数: |
412 次 |
| 最近记录: |