How to use a specific interface on a C# object in IronPython - c#

I have a C# class that implements 2 IEnumerable interfaces. How can I access either interface from IronPython?
My class:
public class MyClass : IEnumerable<TypeA>, IEnumerable<TypeB>
{
IEnumerator<TypeA> IEnumerable<TypeA>.GetEnumerator()
{
return _lstTypeA.GetEnumerator();
}
IEnumerator<TypeB> IEnumerable<TypeB>.GetEnumerator()
{
return _lstTypeB.GetEnumerator();
}
}
I tried the following in Python, but although it runs without errors it does not return any elements from the IEnumerable interface:
x = MyClass()
xA = clr.Convert(x, IEnumerable[TypeA])
for y in xA: print y

I don't like your class design. In particular that you implement two different versions of IEnumerable<T> that return different members. Two versions that return the same members is slightly better, but I still don't like that much.
Implementing IEnumerable so it's consistent with both IEnumerable<T>s isn't possible here. In particular that breaks the OfType and Cast linq methods.
You get overload resolution problems almost everywhere. Methods like Select<T>(this IEnumerable<T> ...) don't know which IEnumerable to take.
You can't use foreach on MyClass
If both TypeA and TypeB are reference types the variance of IEnumerable<out T> comes back to bite you. Since both of them offer IEnumerable<T'> for all their common ancestors.
It doesn't interact well with dynamically types languages
A class being a two different collections at the same time rarely makes sense. It usually indicates that something went wrong in the mapping from concepts to classes.
It's confusing and hard to understand. My intuition tells me it's evil and that I should burn it with fire :P
And Probably several more issues I didn't think of yet.
The work around is simple and clean: Have two separate enumerable properties.
public class MyClass
{
public IEnumerable<TypeA> TypeAs{get{_lstTypeA.Select(x=>x)}};
public IEnumerable<TypeB> TypeBs{get{_lstTypeB.Select(x=>x)}};
}

You need to call methods and properties as you were using reflection (that is actually what it happens under the hood).
In your case you should do:
x = MyClass()
enumerator = IEnumerable[TypeA].GetEnumerator(x)
then you can loop over enumerator:
for y in enumerator:
print y

how i use specified interface
clr.AddReference('Platform.CardHost')
from Platform import CardHost
from Platform.CardHost import ICardHost
host = CardHost.CardHost.CreateInstance('session')
# ICardHost is interface
# inside C#
# public interface ICardHost {
# IExtensionManager ExtensionManager { get; }
em = ICardHost.ExtensionManager.__get__(host)

Related

Good practice for 2 virtual methods that delegate the work to each other

Following situation:
An interface declares 2 methods which do the same action with different parameters.
interface IX
{
string DoTheThing(A a);
string DoTheThing(B b);
}
Now objects of A can be converted to B with some cost and vice versa.
Thus we might want to use an abstract class instead of the interface that would look something like that:
abstract class X
{
public virtual string DoTheThing(A a) { return DoTheThing(a.ConvertToB()); }
public virtual string DoTheThing(B b) { return DoTheThing(b.ConvertToA()); }
}
This way a subclass needs to implement only 1 of the methods if wanted.
However, it also must implement at least one of them, otherwise we get an infinite recursion.
One question is now, whether i should make one of the methods abstract and enforce the implementation?
The problem with that is that i'd have to pick one of the methods and it might be the wrong one for
some of the subclasses and result in more conversions.
So the second question is about whether i'm missing a better solution by some language features or better
design decisions (or whether i'm overthinking this)?
P.S I'm working with C#, but the answer doesn't need to be restricted to C#.

How to use an interface privately

I am attempting to use an interface privately inside of a few different classes. However I wont let me call the function inside the getter you see below:
public abstract class PreFabComponent : IAccountable
{
//This represents the cumulative cost of all members, connectors, and supporting hardware
private double materialsCost;
protected double MaterialsCost
{
get
{
materialsCost = CalculateSelfCost();
return materialsCost;
}
}
// Returns the sum of all Cumulative costs
double IAccountable.CalculateSelfCost()
{
double sum = 0;
foreach (IAccountable item in accountableItemsContatined)
{
sum += item.CalculateSelfCost();
}
return sum;
}
}
Here is the interface
interface IAccountable
{
double CalculateSelfCost();
}
How can I fix this?
You need to do an explicit cast:
private double materialsCost;
protected double MaterialsCost
{
get
{
materialsCost = (this as IAccountable).CalculateSelfCost();
return materialsCost;
}
}
Basically, explicit interface method implementations are separate from other methods of a class. You simply can't call them without an explicit cast to the containing interface. In fact, there is no virtual method CalculateSelfCost in your class, in a manner of speaking.
If you want to know more about this, here is a good start - http://msdn.microsoft.com/en-us/magazine/cc163791.aspx (look specifically for the MethodTable section). You can see that the method tables for the interfaces you're implementing are separate from the method table of your class proper. In the case of implicit interface method implementations, both the main method table and the interface method table contain the reference, while in explicit implementations, the main method table doesn't have the reference at all. Now, details like this don't usually matter at all to the end-programmer, but I hope this satisfied your curiosity :)
This also has a couple of practical reasons unrelated to the internals or encapsulation practices, for example, if you had two explicit implementations of a method with the same signature but on two different interfaces, which one would you be actually calling? Rather than trying to solve the ambiguity, you simply have to always call the method properly, with the explicit interface included.

Wrapping C# classes to use with polymorphism through a common interface

I've got several C# classes each with similar properties.
(They're part of an SDK and their code can’t be changed.)
Person.Name
Product.Name
Order.Name
I want to use these classes polymorphically, but they don’t implement a common interface or derive from a common base class, so that’s not possible.
To get around this, I’d like to wrap each one in another class that does implement a common interface, and wire-up each class property to its corresponding interface property.
What would be a suitable name for the wrapper classes? Wrapper, Decorator, Adaptor, Proxy? Does this pattern have a name? Is there a better approach?
(I don't want to use dynamic duck-typing or an impromptu interface.)
It looks like Adapter, because you are adapting the existing interfaces to the specific requirements.
(I don't want to use dynamic duck-typing or an impromptu interface.)
So what is wrong with a NamedObject?
public class NamedObject
{
public string Name { get; set; }
}
It literally says what it is, nothing less, nothing more.
I'd stick with CodeCaster's idea, and perhaps with a dash of Func<T> for no other reason than I get withdrawal symptoms when I don't use angle brackets...
public class NamedEntity
{
public string Name { get { return _getName(); } }
private Func<string> _getName;
public NamedObject(Func<string> getName)
{
_getName = getName;
}
}
And then call thus:
var named = new[]
{
new NamedEntity(() => person.Name),
new NamedEntity(() => product.Name),
new NamedEntity(() => order.Name)
};
The added benefit with this is when the value of the property changes on the target object, it changes within the NamedEntity reference too via the Func, this means within the life span of the objects you can get away with wrapping them once. You can also do the inverse with Funcs that set values as well as get, and can adapt more properties.
I am not immediately sure what pattern this represents (if any), though I would guess Adapter pattern (which is a type of wrapper pattern). However, it could also be argued to be a Proxy pattern. Not sure really.
Maybe you can just change the namespace and keep the names of the original classes.
Technically, I think the most correct name would be Adapter, see this question.
Adapter is used when you have an abstract interface, and you want to map that interface to another object which has similar functional role, but a different interface.
You don't have abstract interface, but "similar functional role, but a different interface".

Why C# don't accept constructor requirements with parameters on generics?

Working with C# Generics you can have a class like this:
class Foo<T> where T:new() {}
Which means that the type T should have a constructor without parameters. It would be nice if we could have:
class Foo<T> where T : new(string)
{
private T CreateItem()
{
string s="";
return new T(s);
}
}
Is there any reason that Microsoft haven't added this feature to the language?
Is there any reason that Microsoft haven't added this feature to the language?
The feature you describe is a specific case of the of the more general feature "allow a constraint that requires a particular method to exist". For example, you might say:
void M<T>(T t) where T has an accessible method with signature double Foo(int)
{
double x = t.Foo(123);
}
We don't have that feature in C# because features have to be justified by a cost-benefit analysis. That would be a pretty expensive feature from both a design and implementation point of view -- a feature that would drive requirements onto not just C# but every .NET language. What's the compelling benefit that justifies the feature?
Moreover: suppose we did design that feature. How would it be implemented efficiently? The constraints in the generic type system have been carefully designed so that the jitter can generate efficient code once that can then be shared for every reference type. How would we generate efficient code for arbitrary method pattern matching? That sort of efficient dispatch is pretty straightforward when the method's slot can be known at compile time; with this feature we would no longer have that advantage.
The feature you want is the same feature, just with the kind of method restricted to a constructor.
Remember, the purpose of generics is to let you write generically typed code. If you're requiring constraints that are more specific than things that can be captured in the type system then you might be trying to abuse generics.
Rather than try to guess why Microsoft decided on a particular implementation, here's a workaround for you, using the factory pattern
public interface IFactory<T>
{
T CreateItem(string s);
}
class Foo<TFactory,T> where TFactory : IFactory<T>, new()
{
private T CreateItem()
{
var factory = new TFactory();
string s="";
return factory.CreateItem(s);
}
}
Using this pattern, say you have a class Bar which has a constructor taking a single string:
public class Bar
{
public Bar(string laa)
{}
}
You just need a BarFactory which implements IFactory<Bar>
public class BarFactory : IFactory<Bar>
{
public BarFactory () {}
public Bar CreateItem(string s)
{
return new Bar(s);
}
}
Now you can use that factory with Foo
var foo = new Foo<BarFactory,Bar>(); // calls to CreateItem() will construct a Bar
The solution I adopted when I wanted a generic function that invoked a constructor with arguments was to use reflection to find and invoke it.
Given that I had control of both the generic, and all the classes it was implemented over (and this function was the only place those classes were constructed), I think I might have been better to give the classes a default constructor and added an Initialize method in the interface they all implemented.
(A solution that allowed adding static methods in general to an interface would be ideal.)

CollectionBase vs generics

I am migrating an application from .NET 1.1 to .NET 2.0. Should I remove all uses of CollectionBase? If so, what is the best strategy for migration?
Yes, the best classes to look at are in System.Collections.Generic.
I usually use List.
There are two approaches you can use either:
A
public class MyClass
{
public List<MyItem> Items;
}
B
public class MyItemCollection : List<MyItem>
{
}
public class MyClass
{
public MyItemCollection Items;
}
The two approaches only differ very slightly and you only need to use method (B) if you plan on extending the functionality of List.
Here's a link with more info:
http://msdn.microsoft.com/en-us/library/6sh2ey19(VS.80).aspx
With regards to the classes that you've already implemented, you can remove all of the functions which are specified in the IList interface. e.g.
public int Add(InstrumentTradeDataRow instTrade) { return List.Add(instTrade); }
This can be removed because List already implements a type safe Add function for you.
See this link for more information:
http://msdn.microsoft.com/en-us/library/3wcytfd1(VS.80).aspx
Generally, List<T> does most of what you normally want. If you want to customize behaviour, you should inherit from Collection<T> - this has virtual methods so you can tweak behaviour when adding/removing/updating etc. You can't do this with List<T> since there are no (uesful) virtual methods.
I prefer Mark Ingrams A) approach, possibly with a base class you write yourself.
There is another issue with migrating to generics; converting has a tendency to have a certain viral effect. You may find it impossible to stop before you're all the way through. If you THOUGHT you were going to spend a couple of hours doing SOME generics, you'll often find yourself spending several days doing ALL the generics.
You can/should avoid this by giving your new classes operator overloads to/from list
public static implicit operator MyClass(List m)
{
// code to convert from m to MyClass
}
public static explicit operator List(MyClass m)
{
// code to convert from MyClass list
}
These are really just stopgaps. You can use "find usages" on these at any later stage to determine which places have not been fully converted. When all usages are removed, you can delete the casts.
I generally perfer to make the cast from MyClass to List explicit (this is the way you dont want to go) and the other implicit.
The best approach would then normally be to start at the TOP of your layers, close to the presentation layer and work downwards. (This is opposite of what you might think. If you make the cast from MyClass to List implicit it doesnt matter which end you start)

Categories