我有一个课程,我可以阅读,但不会因为公司政策而写。我的项目中有以下结构。
public class Name // can not touch this class OR modify it
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string GetNames()
{
return FirstName + " " + LastName;
}
}
public class Details
{
// some methods and properties.
public Name LoadName() // This method return type i can not change as this method is used in ObjectDataSource for GridView
{
var names = new Name();
if (txtInpput.Text == "Jermy")
{
names.FirstName = "Jermy";
names.LastName = "Thompson";
}
else
{
names.FirstName = "Neville";
names.LastName = "Vyland";
}
return
names;
}
}
不,我想在名为class Name
的{{1}}中添加额外的属性,并使用"Email Address"
LoadName()方法返回包含{{1}的类型也是。因为我必须使用该方法,所以我无法将返回类型class Details
更改为其他内容。
我可以扩展**Email Address**
和Name
class Name
方法以包含新创建的属性,但这不会有帮助,因为我无法在overrides
方法中更改返回类型
我不确定这是否可能,但只是想知道是否有任何解决方案。
GetNames()
答案 0 :(得分:3)
如果您无法更改方法的签名,则您的调用者需要进行一些转换。这不是最佳选择,但您仍然可以这样做:
public class NameWithEmail : Name {
public string EMail {get;set;}
}
...
public Name LoadName() {
...
return new NameWithEmail(); // OK because NameWithEmail extends Name
}
现在调用者需要知道新类型,进行演员表并通过它访问电子邮件:
NameWithEmail name = Details.LoadName() as NameWithEmail;
if (name != null) {
Console.WriteLine("{0} {1} : {2}", name.FirstName, name.LastName, name.EMail);
}
最棘手的部分是将新属性绑定到数据网格。 This answer解释了如何做到这一点。
答案 1 :(得分:1)
试试这个:
public class Name // can not touch this class OR modify it
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string GetNames()
{
return FirstName + " " + LastName;
}
}
public class Name1:Name {
public string EmailAddress { get; set; }
public override string GetNames()
{
return FirstName + " " + LastName+" "+EmailAddress;
}
}
public class Details
{
// some methods and properties.
public Name LoadName() // This method return type i can not change as this method is used in ObjectDataSource for GridView
{
TextBox txtInpput = new TextBox();
var names = new Name();
if (txtInpput.Text == "Jermy")
{
names.FirstName = "Jermy";
names.LastName = "Thompson";
}
else
{
names.FirstName = "Neville";
names.LastName = "Vyland";
}
return
names;
}
}
public class Details1:Details {
public override Name LoadName()
{
TextBox txtInpput = new TextBox();
var names = new Name();
if (txtInpput.Text == "Jermy")
{
names.FirstName = "Jermy";
names.LastName = "Thompson";
}
else
{
names.FirstName = "Neville";
names.LastName = "Vyland";
}
return
names;
}
}