Ste*_*ger 2 .net c# constructor
问题:我想在其构造函数中将数据库数据填充到类的实例的属性和字段中.
public class Profile : ProfileOverview
{
public Profile()
{ }
public Profile(long ProfileId)
{
using (System.Data.IDbCommand cmd = Settings.DAL.CreateCommand("SELECT * FROM Profiles WHERE ProfileId = @__in_profileid"))
{
Settings.DAL.AddParameter(cmd, "__in_profileid", ProfileId);
this = Settings.DAL.GetClass<Models.Profile>(cmd);
} // End Using cmd
} // End Constructor
... (some properties and fields)
}
Run Code Online (Sandbox Code Playgroud)
问题是,编译器说它不能分配"this",因为它是写保护的.我是否真的有必要更改我的数据库抽象层以将"this"传递给它,或者我能以某种方式这样做吗?
问题是,GetClass调用Activator.CreateInstance创建一个新的实例Models.Profile,我宁愿保持这种方式(因为GetClass是一个函数,而不是一个过程).
你不能分配this.考虑像这样改变你的模式:
public class Profile : ProfileOverview
{
public Profile()
{ }
public static Profile Get(long ProfileId)
{
using (System.Data.IDbCommand cmd = Settings.DAL.CreateCommand("SELECT * FROM Profiles WHERE ProfileId = @__in_profileid"))
{
Settings.DAL.AddParameter(cmd, "__in_profileid", ProfileId);
return Settings.DAL.GetClass<Models.Profile>(cmd);
} // End Using cmd
}
... (some properties and fields)
}
Run Code Online (Sandbox Code Playgroud)
更新
基于来自@CodeInChaos和@weston的评论,我在这里添加的上述代码是糟糕的设计是公平的.理想情况下,静态加载器方法将生活在一个不同的类中,其目的是加载您的Profile.请考虑以下基本示例:
public class Profile : ProfileOverview
{
public Profile() { }
... (some properties and fields)
}
public class ProfileHelper
{
public Profile LoadProfileById(long ProfileId)
{
using (System.Data.IDbCommand cmd = Settings.DAL.CreateCommand("SELECT * FROM Profiles WHERE ProfileId = @__in_profileid"))
{
Settings.DAL.AddParameter(cmd, "__in_profileid", ProfileId);
return Settings.DAL.GetClass<Models.Profile>(cmd);
}
}
}
Run Code Online (Sandbox Code Playgroud)