Hungry Mind , Blog about everything in IT - C#, Java, C++, .NET, Windows, WinAPI, ...

Type system covariance and contravariance

Полагаю, многие разработчики не знают, что такое ковариантность/контравариарность системы типов. К примеру, в версии 1.5 языка Java появилась возможность использовать тип класса-наследника в объявлении замещающей функции:

 0: /**
 1:  *
 2:  */
 3: package com.chabster.covariance;
 4:
 5: /**
 6:  * @author Chabster
 7:  */
 8: public class Container
 9: {
10:   class A
11:   {
12:      A some() {
13:         return (this);
14:      }
15:   }
16:
17:   class B extends A
18:   {
19:      @Override
20:      B some() {
21:         return (this);
22:      }
23:   }
24:
25: }

В С++ такая возможность существует уже давно, а вот в C# все еще отсутствует. Полагаю, это связано с нестыковкой сигнатур методов в C# и IL. Вот, что говорит по этому поводу Standard ECMA-335 Common Language Infrastructure (CLI) 4th edition (June 2006):

A method signatures is composed of

  • a calling convention,
  • the number of generic parameters, if the method is generic,
  • a list of zero or more parameter signatures—one for each parameter of the method—and,
  • a type signature for the result value, if one is produced.

Получается, что IL код различает методы, которые отличаются лишь типом возврата, а C# - нет. Как и любой существующий на данный момент управляемый .NET-язык. С другой стороны этот недостаток можно элементарно восполнить. Вариант реализации предлогаю расценивать, как домашнее задание для читателя :).

В некоторых моментах C#, все же, поддерживает ковариантность и контравариантнось. Но для начала выясним что это такое.

Ковариантность (covariance) и контравариантнось (contravariance)

Ковариантностью называют сохранение формы при преобразовании. Соответсвенно, ковариантным называется преобразование, сохраняющее форму (свойства).

Например, оператор F(x) = x*2 является ковариантным касательно отношения % (делимость). Т.е. из x%y следует, что F(x)%F(y).

Контравариантностью называют обращение формы при преобразовании. Соответсвенно, контравариантным называется преобразование, обращающее форму.

Например, оператор F(x) = -x является контравариантным касательно отношения > (больше). Т.е. из x>y следует, что F(x)<F(y).

Оба этих понятия нельзя правильно обобщить поскольку в каждой науке оно выглядит по-своему. Рассмотрим их в самой интересной для нас области - программирование!

Ковариантность и контравариантнось в системе типов языков программирования

Рассмотрим пример C# кода:

class A {
    A[] aArr = new B[] { };
}

class B : A {
}

Пусть « обозначает отношение is a для типов. Поэтому B«A. Оператор Arrize({T}) = {T[]} является ковариантным касательно отношения is a для ссылочных типов т.к. из B«A следует B[]«A[].

Возвращаясь к первому Java примеру можно сказать, что оператор Methodize({SuperT virtMethod(T1,T2,...)}) = {SubT virtMethod(T1,T2,...)} является ковариантным касательно отношения override между методами.

Ковариантность и контравариантнось в системе типов C#

В C# есть ковариация, связанная с делегатами:

class A {
}

class B : A {
}

delegate A SomeDelegate();

static B SomeMethod() { return (null); }

static SomeDelegate sd = SomeMethod;

Типы возвращаемых значений метода и делегата различны, но совместимы.

В C# есть и контравариация, связанная с делегатами:

class A {
}

class B : A {
}

delegate void SomeDelegate(B b);

static void SomeMethod(A a) { }

static SomeDelegate sd = SomeMethod;

Сигнатуры метода и делегата различны, но совместимы, правда, уже в обратном направлении.

Это все, конечно, хорошо, вот только...

class A {
}

class B : A {
}

delegate T SomeDelegate<T>();

static B SomeMethod() { return (null); }

static SomeDelegate<B> sdB = SomeMethod;

static SomeDelegate<A> sdA = sdB;

... последняя строчка вызывает ошибку компиляции.

В целом, вариантность - очень полезный механизм, если им правильно пользоваться.

32 коммент.:

Анонимный комментирует...

I do not know whether it's just me or if everybody else experiencing issues with your site. It looks like some of the text within your content are running off the screen. Can somebody else please provide feedback and let me know if this is happening to them as well? This might be a issue with my browser because I've had this happen previously.

Appreciate it
Feel free to surf my site ; electronices

Анонимный комментирует...

Hi there, this weekend is nice in support of me, because this moment i am
reading this great informative piece of writing here
at my home.
Feel free to visit my blog ... epl transfer news bbc

Анонимный комментирует...

What's up Dear, are you genuinely visiting this site regularly, if so then you will absolutely get fastidious experience.

Also visit my web page ... Air Duct Cleaning Tampa
Also visit my page : Duct cleaning Tampa

Анонимный комментирует...

Right here is the perfect site for everyone who really wants to find out about this topic.

You realize a whole lot its almost hard to argue with
you (not that I actually will need to…HaHa).
You definitely put a new spin on a topic that has been discussed for decades.

Wonderful stuff, just excellent!

Feel free to visit my site :: smart circle directv braves

Анонимный комментирует...

Excellent goods from you, man. I have understand your stuff previous to and you
are just extremely magnificent. I actually like what you've acquired here, really like what you are saying and the way in which you say it. You make it entertaining and you still take care of to keep it smart. I cant wait to read far more from you. This is really a terrific web site.

Also visit my web page - affordable appliance repair Houston

Анонимный комментирует...

Can you tell us more about this? I'd care to find out some additional information.

Review my blog post ... smart circle directv braves

Анонимный комментирует...

Today, while I was at work, my cousin stole my iPad and tested to see
if it can survive a thirty foot drop, just so she can be a youtube sensation.
My iPad is now broken and she has 83 views. I know this is entirely off topic but I had to share it
with someone!

Also visit my blog; appliance repair tampa rates

Анонимный комментирует...

It's hard to come by experienced people for this subject, but you sound like you know what you're talking about!

Thanks

My web-site digital marketing

Анонимный комментирует...

I have read so many content about the blogger lovers but this article is really a pleasant article, keep it up.



my weblog - advertising & marketing

Анонимный комментирует...

Hello, everything is going sound here and ofcourse every one is sharing data, that's in fact excellent, keep up writing.

Look into my blog: network marketing company

Анонимный комментирует...

certainly like your web-site however you have to test the spelling on
quite a few of your posts. Several of them are rife with spelling problems and I in finding it very troublesome
to inform the reality nevertheless I'll definitely come back again.

Feel free to visit my weblog ... professional appliance repair Brandon

Анонимный комментирует...

Fastidious respond in return of this difficulty with solid arguments and describing everything
regarding that.

Also visit my website appliance repair Temple Terrance

Анонимный комментирует...

Greetings! Very helpful advice in this particular post!
It is the little changes that produce the biggest changes.

Thanks a lot for sharing!

My web blog - washer and dryer appliance repair Safety Harbor FL

Анонимный комментирует...

My brother recommended I might like this web site. He was totally right.

This post truly made my day. You cann't imagine just how much time I had spent for this info! Thanks!

Here is my web blog: subzero refrigerator & appliance repair Clearwater FL

Анонимный комментирует...

Really no matter if someone doesn't know after that its up to other visitors that they will help, so here it happens.

Stop by my blog ... subzero refrigerator & appliance repair Dunedin FL

Анонимный комментирует...

What's up to every body, it's my first go to
see of this weblog; this blog carries amazing and genuinely good
material in support of readers.

My page ... visa secured credit cards

Анонимный комментирует...

Whoa! This blog looks exactly like my old one!
It's on a completely different subject but it has pretty much the same page layout and design. Wonderful choice of colors!

Also visit my web-site - michael thurman six week body makeover

Анонимный комментирует...

What's up to all, the contents present at this web site are in fact amazing for people knowledge, well, keep up the nice work fellows.

Feel free to surf to my webpage; network marketing vt scam

Анонимный комментирует...

Saved as a favorite, I really like your website!

my site smart circle directv reviews

Анонимный комментирует...

Yes! Finally something about dentist marketing.

Here is my web site Smart Circle Directv

Анонимный комментирует...

I believe this is one of the most important information for me.
And i am satisfied studying your article. But want
to remark on few basic issues, The site style is wonderful,
the articles is truly nice : D. Excellent task, cheers

Also visit my web site: whole life insurance rate

Анонимный комментирует...

It's appropriate time to make some plans for the longer term and it's time to be
happy. I've read this publish and if I could I want to recommend you few fascinating things or tips. Maybe you could write next articles regarding this article. I want to read even more things about it!

Also visit my website :: clean jokes

Анонимный комментирует...

Pretty! This has been an extremely wonderful article. Thank
you for providing this information.

Also visit my website ... child term life insurance

Анонимный комментирует...

Hello to every one, the contents present at this web site are genuinely remarkable
for people experience, well, keep up the good work fellows.


My web site smart circle directv

Анонимный комментирует...

Nice post. I was checking constantly this blog and I'm impressed! Extremely useful information particularly the last part :) I care for such info a lot. I was looking for this certain information for a long time. Thank you and best of luck.

my homepage online term life insurance quotes

Анонимный комментирует...

An outstanding share! I have just forwarded this onto a friend who has been conducting a
little research on this. And he actually bought me dinner due to
the fact that I discovered it for him... lol.
So allow me to reword this.... Thank YOU for the meal!
! But yeah, thanks for spending the time to discuss this topic here on your
internet site.

Feel free to visit my weblog - smart circle directv sam's club

Анонимный комментирует...

Right now it appears like Drupal is the preferred blogging
platform available right now. (from what I've read) Is that what you are using on your blog?

Also visit my site :: b2b marketing

Анонимный комментирует...

Great blog here! Also your web site loads up very fast!
What web host are you using? Can I get your affiliate link to your host?
I wish my site loaded up as quickly as yours lol

Also visit my web-site ... instant online car insurance

Анонимный комментирует...

Wow, this article is fastidious, my younger sister is analyzing these things, so I am going to
let know her.

Review my web page smart circle directv international

Анонимный комментирует...

Howdy! I know this is somewhat off topic but I was wondering which blog platform are you using for
this website? I'm getting tired of Wordpress because I've had problems with hackers and I'm looking at options for another platform. I would be fantastic if you could point me in the direction of a good platform.

Feel free to surf to my site - smart circle directv

Анонимный комментирует...

I rarely comment, however i did some searching and wound up here "Type system covariance and contravariance".
And I do have a couple of questions for you if you don't mind. Is it just me or does it look like some of these remarks look as if they are written by brain dead visitors? :-P And, if you are writing on other online sites, I'd like to keep up with everything fresh you have to post.
Would you make a list of all of all your public pages like your linkedin profile, Facebook page or
twitter feed?

Here is my homepage :: new cellulite treatment

Анонимный комментирует...

Hi to every body, it's my first go to see of this blog; this web site consists of awesome and really fine data designed for visitors.

My blog post ... poseur Volet

Отправить комментарий

Copyright 2007-2011 Chabster