I have a DTO as follows.
public class PersonDTO
{
public int Id {get;set;}
public string Name {get;set;}
}
Assuming I have got a requirement to implement the following interface in the PersonDTO.
public Interface ImplementPerson<T>()
{
int GetName();
}
I do not want to make changes to PersonDTO except inheriting ImplementPerson, what options I have to implement GetName method? Finally, when I create an object of PersonDTO I should be able to have GetName() in the intellisense.
public class PersonDTO : ImplementPerson<PersonDTO>
{
public int Id {get;set;}
public string Name {get;set;}
}
CodePudding user response:
Try extension class
using System;
public class PersonDTO
{
public int Id {get;set;}
public string Name {get;set;}
}
public static class PersonDTOExtension {
public static int GetName(this PersonDTO p) {
// implement
return p.Id;
}
}
class HelloWorld {
static void Main() {
var p = new PersonDTO();
Console.WriteLine(p.GetName());
}
}
CodePudding user response:
You can use an abstract class and implement the method in it
public class PersonDTO: Parent
{
public int Id {get;set;}
public string Name {get;set;}
}
abstract class Parent {
public string GetName(string name) {
return name;
}
}
//
static void Main() {
var p = new PersonDTO();
p.GetName(p.Name);
}
