Object Identity and implicit Interface Implementations
Hi there,
I am excited about LINQ. To use it in our applications we need the following:
- A an object loaded from several queries should be the same, that is only instanciated once in memory (at least as an option). [This is what typical O/R Mappers do]. However there are variations of this pattern when it comes to implementing nested transactions on memory objects.
- If I load any object from the database that has a name property/column and let there be an interface INamedObject that requires one name property. Can I then cast the retrieved object to INamedObject without any hassel? If so, then this means I could cast loaded objects to any interface that they could implement. Much like delegates only require the signature to be corrrect only.
This is useful when passing the object to a method that accepts objects of type INameObject.
However there is a semantical problem with this approach, as the interface or contract will only check for members not for behaviour. I am not sure what the Spec# guys would say to this?
What is your answer regarding the application of business logic to loaded objects using interfaces?
Thanks
Tim
Please reply to:tfischer@tangible.de, Tim F. Fischer CEO , tangible engineering
Implicit typing isn't, I believe, supported yet in the CLR. However, if you hunt on CodeProject, there are examples of how to go about emulating such a thing.
You could, for example, use lightweight code generation. Here's a sketch of how I think it could work:
| |
public class NamedObject<T>: INamedObject { private readonly T _obj; public T InternalObject { get { return _obj; } } public NamedObject(T obj) { this._obj = obj; if (GetName == null) // you'd want to lock this section for thread safety { // use lightweight code generation to // create a delegate to retrieve the // name property from obj // store the delegate in GetName } } public string Name { get { return GetName(this.InternalObject); } } private static delegate string NameGetter(T obj); private static NameGetter GetName; // guessing that this explicit cast operator may work -- haven't tried it public explicit operator NamedObject<T>(T obj) { return new NamedObject(obj); } }
|
If the explicit cast operator works, I think you could take some object T and then do:
| |
foo.MethodTakingINamedObject((NamedObject<namedType>) namedObj);
|
otherwise I'd say
| |
foo.MethodTakingINamedObject(new NamedObject<namedType>(namedObj));
|
Because static members of a generic class are static to the specialization of the generic, there will be a version of GetName for each type T, and because you can use LCG to create a strong-typed version of GetName per T, you can get pretty good speed. Of course, implicit typing *would* be nice, but there are workarounds. Hopefully the above is useful to you.
Forgive any mistakes here -- I'm doing this in my head based on work I did for http://www.codeproject.com/csharp/GenericOperators.asp.