解决这个问题有两种方法:
创建一个具有所有这些通用属性的基类,并从中派生其他属性。
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);