你能对下面的实现提供建议吗?
我正在尝试实现一种从Class1.Process()
调用Class2.Save()
方法的通用方法。
class Program
{
static void Main(string[] args)
{
IClass2 c2= new Class2();
Class1 c1 = new Class1(c2);
c1.Process<Student>(new Student());
}
}
public interface IClass1 {
bool Process<T>(T t) where T : new();
}
public class Class1 : IClass1
{
IClass2 _repo;
public Class1(IClass2 repo)
{
_repo = repo;
}
public bool Process<T>(T t) where T : new()
{
_repo.Save (t);
return true;
}
}
public interface IClass2 {
void Save(Student e);
void Save(Teacher e);
}
public class Class2 : IClass2
{
public void Save(Student e)
{
return;
}
public void Save(Teacher e)
{
return;
}
}
public class Student { }
public class Teacher { }
我不喜欢使用反射或投射。有没有人可以帮助解决这个问题,或者提出替代方法。
发布于 2019-06-04 05:31:59
像这样怎么样?
我已经更改了约束,而不是将方法约束改为类约束。并且具有独立的类,这两个类都符合Repository接口。
class Program
{
static void Main(string[] args)
{
StudentRepository studentRepository = new StudentRepository();
IProcessor<Student> processor = new Processor<Student>(studentRepository);
processor.Process(new Student());
}
}
public interface IProcessor<T> where T : new()
{
bool Process(T t);
}
public class Processor<T> : IProcessor<T> where T : new()
{
IRepository<T> _repo;
public Processor(IRepository<T> repo)
{
_repo = repo;
}
public bool Process(T t)
{
_repo.Save(t);
return true;
}
}
public interface IRepository<T> where T : new()
{
void Save(T e);
}
public class StudentRepository : IRepository<Student>
{
public void Save(Student e)
{
return;
}
}
public class TeacherRepository : IRepository<Teacher>
{
public void Save(Teacher e)
{
return;
}
}
public class Student { }
public class Teacher { }
发布于 2019-06-04 11:02:28
给定您的约束(在我看来有点人为,尽管我见过更糟糕的情况),您可以在不反射、不强制转换和不更改Process
方法的泛型性质的情况下实现这一点,只需反转调用方向,以便知道自己类型的对象可以在存储库中调用正确的方法。
首先声明你的域对象是“可保存的”:
public interface ISaveable
{
void Save(IClass2 repo);
}
public class Student : ISaveable
{
public void Save(IClass2 repo)
{
repo.Save(this);
}
}
public class Teacher : ISaveable
{
public void Save(IClass2 repo)
{
repo.Save(this);
}
}
现在,每个域对象都知道如何保存自己。您所要做的就是为它提供一个存储库,您可以在Process
方法中执行此操作。
public class Class1 : IClass1
{
IClass2 _repo;
public Class1(IClass2 repo)
{
_repo = repo;
}
public bool Process<T>(T t) where T : ISaveable
{
t.Save(_repo);
return true;
}
}
https://stackoverflow.com/questions/56434564
复制相似问题