この問題には2つのアプローチがあります。
これらすべての共通のプロパティを持つ基本クラスを作成し、そこから他のプロパティを派生させます。
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();
または、3つのクラスが実装するインターフェースを定義します。
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);