은이 문제에 대한 두 가지 방법이 있습니다.
public abstract class MyBaseClass
{
public string Name { get; set; }
public string Signature { get; set; }
public int Checksum { get; set; }
}
public class ClassX : MyBaseClass
{
// Add the other properties here
}
public class ClassY : MyBaseClass
{
// Add the other properties here
}
public class ClassZ : MyBaseClass
{
// Add the other properties here
}
형 MyBaseClass의 매개 변수가됩니다 도우미 방법 : 지금은 액세스 할 수 있기 때문에,
public void MyHelperMethod(MyBaseClass obj)
{
// Do something with obj.Name, obj.Siganture and obj.Checksum
}
는 또한 MyBaseClass에서 도우미 메서드를 배치하는 것이 좋습니다 수 있지만 매개 변수가없는 것을 직접 등록 :
public abstract class MyBaseClass
{
public string Name { get; set; }
public string Signature { get; set; }
public int Checksum { get; set; }
public void CreateChecksum() // Your helper method
{
Checksum = Name.GetHashCode()^Signature.GetHashCode();
}
}
그런 다음 당신은 당신의 객체에서 직접 호출 할 수 있습니다 :
objA.CreateChecksum();
objB.CreateChecksum();
objB.CreateChecksum();
아니면 세 가지 클래스가 구현하는 인터페이스 정의 :
이
public interface IMyInterface
{
string Name { get; set; }
string Signature { get; set; }
int Checksum { get; set; }
}
public class ClassX : IMyInterface
{
public string Name { get; set; }
public string Signature { get; set; }
public int Checksum { get; set; }
// Add the other properties here
}
public class ClassY : IMyInterface
{
public string Name { get; set; }
public string Signature { get; set; }
public int Checksum { get; set; }
// Add the other properties here
}
public class ClassZ : IMyInterface
{
public string Name { get; set; }
public string Signature { get; set; }
public int Checksum { get; set; }
// Add the other properties here
}
도우미 방법은 형 IMyInterface의 매개 변수가됩니다 :
public void MyHelperMethod(IMyInterface obj)
{
// Do something with obj.Name, obj.Siganture and obj.Checksum
}
당신은 같은 MyHelperMethod를 호출 할 수 있습니다
이
MyHelperMethod(objA);
MyHelperMethod(objB);
MyHelperMethod(objC);
이 코드를 "구조적 입력"이라고하며 스칼라와 같은 언어로 제공됩니다. C# 4는 '동적'(* 구조적 타이핑이 아닙니다)을 소개합니다. C#이 슬리브를위한 다른 트릭을 가지고 있는지 전혀 알지 못합니다. 표준 접근 방식은 적절한 인터페이스를 추가하는 것입니다. –