【发布时间】:2017-12-28 17:07:46
【问题描述】:
主类:
public class ClP_Login
{
private Form vrcView;
private I_Repository<I_Identifiable> vrcRepository = null;
public ClP_Login(Form vrpView)
{
vrcView = vrpView;
SetTheme();
}
private void SetTheme()
{
if(vrcView !=null)
vrcView.BackColor = Cl_BaseColor.StandardBackground;
}
public void CreateNewUser()
{
ClE_User test = new ClE_User();
test.Name = "test name";
test.Password = "";
Cl_RepositoryFactory vrlFactory = new Cl_RepositoryFactory();
vrcRepository = vrlFactory.CreateRepository(E_Repositories.User);
vrcRepository.Add(test);
}
}
Cl_RepositoryFactory 类:
public class Cl_RepositoryFactory
{
public virtual I_Repository<I_Identifiable> CreateRepository(E_Repositories vrpRepository)
{
I_Repository<I_Identifiable> vrlRepository = null;
switch (vrpRepository)
{
case E_Repositories.User:
vrlRepository = new Cl_UserRepository() as I_Repository<I_Identifiable>;
break;
}
return vrlRepository;
}
}
枚举 E_Repositories:
public enum E_Repositories
{
User
}
I_Identifiable 接口:
public interface I_Identifiable
{
int Id { get; set; }
}
I_Repository 接口:
public interface I_Repository<T>
{
T GetById(Guid id);
T GetByQuery(Queue query);
void Add(T item);
void Remove(T item);
void Update(T item);
}
Cl_UserRepository 类:
public class Cl_UserRepository : I_Repository<ClE_User>
{
public void Add(ClE_User item)
{
MessageBox.Show("Created new User");
}
public ClE_User GetById(Guid id)
{
throw new NotImplementedException();
}
public ClE_User GetByQuery(Queue query)
{
throw new NotImplementedException();
}
public void Remove(ClE_User item)
{
throw new NotImplementedException();
}
public void Update(ClE_User item)
{
throw new NotImplementedException();
}
}
还有 ClE_User 类:
public class ClE_User : I_Identifiable
{
public int Id { get; set; }
public string Name { get; set; }
public string Password { get; set; }
}
问题是,为什么我使用 vrcRepository 得到空引用异常? vrlFactory.CreateRepository(E_Repositories.User); return null,我不知道为什么,请帮忙
【问题讨论】:
-
因为您试图将
Cl_UserRepository转换为I_Repository<I_Identifiable>并且这不是一回事,所以... as ...位返回null。 -
此外,您在此处使用的所有类型前缀(
Cl_、I_等)都会使您的代码难以阅读。 -
如果
I_Repository上的泛型类型T是协变的,它会起作用,但它不是也不能是因为T被用作接口的输入。如果该演员确实有效,您可以将不是ClE_User的东西传递给Add、Remove和Update的任何方法。 -
@DavidG 抱歉代码不可读,我只是尝试应用我公司采用的标准,对此无能为力。
-
哇哦,那你们公司的标准真的很烂!随意告诉他们我说过:)
标签: c# .net nullreferenceexception factory factory-pattern