开发者

Generic interface members

I've asked this question yesterday and got lots of good answers, only I just realized 开发者_运维技巧my question was wrong and here I want to rephrase it.

I have this interface

public interface IFoo<T>
{
   T Value();
}

With this members

public class Bar : IFoo<string>
{
   string Value(){return "test";}
}
public class Bar2 : IFoo<int>
{
   int Value(){return "1";}
}

This works perfectly, but now I want to make a class that has a property that can be either Bar or Bar2 so like this

public class Test
{
  IFoo test;
}

Only this will not compile because Ifoo needs to have a generic type. Only I don't know in advance whether I will use Bar2 or Bar.

I hope I explained it well, but if not, I'll try to make it more clear.

Explaination

I'm trying (just for fun's sake) to create a Dicom api (medical imaging etc). Part of the dicom standard are some ValueRepresentations (VR's). These are types that are used to store (meta)information of the image.

Such VR's are for example: AgeString, Date, UnsignedShort, SequenceOfItems.

For all of these VR's I want to have some methods that all of them have to implement (encoding etc). But I all want them to be able to store a value. Whether this is a Int, or a DateTime or a String, shouldn't this be put in the Interface?


You have to make your Test class generic as well:

public class Test<T>
{
   IFoo<T> test;
}


You can always make a general interface, in the same way that there's an IEnumerable<T> and an IEnumerable.

public interface IFoo
{
    object Value();
}

Implementation

public class Bar : IFoo<string>, IFoo
{
   public string Value(){return "test";}
   object IFoo.Value(){return Value();}
}
public class Bar2 : IFoo<int>, IFoo
{
   public int Value(){return 1;}
   object IFoo.Value(){return Value();}
}

Test

IFoo b = new Bar();
IFoo b2 = new Bar2();
Console.WriteLine(b.Value());
Console.WriteLine(b2.Value());


You want to use two different classes the same way, but you let them implement different interfaces (different by their type parameter). Why?

Do you really need to strictly specify what type the return value of the method is? How would you handle that different return types in your Test class? Think about it and you may realize that it is enough to return an object. Otherwise you need to make the Test class generic as well.

Best Regards
Oliver Hanappi

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜