我有3个班级,经理,TeamLead,雇员。这些都是在我使用实体框架时从数据库生成的。我在这里不能做任何更改。
Class Manager()
{
string AddressLine1;
string AddressLine2;
string AddressLine3;
.
.
//Some other props
}
Class TeamLead()
{
string AddressLine1;
string AddressLine2;
string AddressLine3;
.
.
//Some other props
}
Class Employee()
{
string AddressLine1;
string AddressLine2;
string AddressLine3;
.
.
//Some other props
}
现在我在另一个程序集中的另一个类,
Class AddressDetails
{
string AddressLine1;
string AddressLine2;
string AddressLine3;
}
当前的代码是
Class WorkingPlace
{
Manager _manager;
TeamLead _teamLead;
Employee _employee;
// all the above obejects getting filled in various functions in this class
AddressDetails _addressDetails;
private SomeMethod1()
{
.
.
//doing some works
.
.
FillAddress("Manager");
}
private SomeMethod2()
{
.
.
//doing some works
.
.
FillAddress("TeamLead");
}
private FillAddress(string type)
{
if(type == "Manager")
{
_addressDetails.AddressLine1 = _manager.AddressLine1;
_addressDetails.AddressLine1 = _manager.AddressLine1;
_addressDetails.AddressLine1 = _manager.AddressLine1;
}
else if( type == "TeamLead")
{
_addressDetails.AddressLine1 = _teamLead.AddressLine1;
_addressDetails.AddressLine1 = _teamLead.AddressLine1;
_addressDetails.AddressLine1 = _teamLead.AddressLine1;
}
}
}
我希望这样,
FillAddress<T>(T typeObj)
{
_addressDetails.AddressLine1 = typeObj.AddressLine1;
_addressDetails.AddressLine1 = typeObj.AddressLine1;
_addressDetails.AddressLine1 = typeObj.AddressLine1;
}
//and Call it as,
FillAddress<Manager>(_manager);
有可能,我是Generics的新手,我想有效地编码。高手请帮帮我。除此之外,还有其他任何评论让我知道。
答案 0 :(得分:2)
没有回答问题,但我认为需要重构代码, 为了避免在此处重复代码, 考虑创建Address类,并将其添加为所有其他类的引用
Class AddressDetails
{
string AddressLine1;
string AddressLine2;
string AddressLine3;
}
然后将其他课程设置为
class Manager
{
AddressDetails address;
public Manager(AddressDetails address){
this.address=address;
}
}
class Employee
{
AddressDetails address;
public Manager(AddressDetails address){
this.address=address;
}
}
更好的是,为所有员工使用基类,因为Manager和TeamLead都是员工,并且都有地址。让其他人从中衍生出来。
现在要回答您的问题,请从AddressDetails类派生一个接口,然后让您的其他类实现它。然后创建您的通用方法
FillAddress(IAddressable employee, Addresdetails newAddress)
{
employee.AddresssLine1=newAddress.AddressLine1;
..........
}
答案 1 :(得分:0)
Here是有关通用方法的MSDN优秀文章。它应该解释您需要知道的一切。
回答您的问题:
是,这是可能的。
格式化通用方法的猜测的方法是正确的。另外,您可以省略ObjectID
部分,如上述文章所述,因为编译器将从参数中推断出类型。
答案 2 :(得分:0)
如我所见,您可能需要进行一些反思。假设您已经实例化了void FillAddress<T>(T value){
var typeInfo = typeOf(value);
_addressDetails.AddressLine1 = typeInfo.GetProperty("AddressLine1")?.GetValue(value) as string;
_addressDetails.AddressLine2 = typeInfo.GetProperty("AddressLine2")?.GetValue(value) as string;
_addressDetails.AddressLine3 = typeInfo.GetProperty("AddressLine3")?.GetValue(value) as string;
}
,则可以执行以下操作:
LoginViewController
MainTabController