Generic method for Similar Objects
C# 4.0 If i have N classes(Entities) with completely the same properties, they don’t have any common interface or any common inheritance I want to have method to be able to pass any of their instances, without copy any properties from one object to another. I think there should be a couple of ways of doing this in .NET 4.0.
e.g somehow using var or dynamik keywords or using generic types. May be something like that:
开发者_运维问答 public void MyMethod<MyType>(AnyType myInstance)
{
Type myType = typeof(T);
myInstance = myInstance as myType;
AppendToFile(myInstance.Field1);
AppendToFile(myInstance.Field2);
}
Now i am investigating that, may be someone have any ideas about that.
If you don't want to or can't derive them or add an interface, then you will have to use dynamic
I believe this will do it, assuming AppendToFile takes dynamic parameters or the Field1 and Field2 are always the same types.
public void MyMethod(dynamic myInstance)
{
AppendToFile(myInstance.Field1);
AppendToFile(myInstance.Field2);
}
The best way would be to change the classes to just implement the interface.
Another approach would be to create the interface that you desire, and then create a default implementation of the interface that just wraps a dynamic object and implements the interface. Then any methods in this default implementation just become pass-throughs to the underlying dynamic.
This would allow you to consistently work with the IMyInterface interface instead of working with the dynamics directly.
For example:
public interface IMyInterface
{
string Field1 { get; }
string Field2 { get; }
}
public class MyDefaultInterface : IMyInterface
{
private Dynamic _dynamic;
public MyDefaultInterface(dynamic target)
{
_dynamic = target;
}
public string Field1 { get { return _dynamic.Field1; } }
public string Field2 { get { return _dynamic.Field2; } }
}
If you're looking to use dynamic
, you can use this:
public void MyMethod(dynamic myInstance)
{
AppendToFile(myInstance.Field1); //note: you will get no intellisense support
AppendToFile(myInstance.Field2);
}
One way is to use reflection (not .NET 4.0 specific):
object field1Value = myType.GetField("Field1").GetValue(myInstance);
I have to ask, is it not possible to change the classes to implement the same interface?
精彩评论