| Ylbtech-microsoft-csharpsamples:ylbtech-languagesamples-simplevariance |
| 1.A, example (sample) back to top |
The simplevariance sample program demonstrates C # 4.0 support for covariance and contravariance when using generic types in delegates and interfaces. In C # 3.0, generic types are fixed. Therefore, this example compiles correctly in C # 4.0, but it cannot be compiled in earlier versions of C #.
A program first declares two simple classes and two delegates:
class Animal {}classCatAnimal {}Func1<t> (); Action1<t> (T a);
Then, implement these delegates and use these classes:
Func1<catcat(); Action1<AnimalConsole. WriteLine (ANI); };
Then the allocations that require covariance and contravariance support:
Func1<Animal> Animal = Cat; Action1<Cat> cat1 = act1;
The latter set of assignments works correctly in C # 4.0, but does not work in earlier versions of C #. The first assignment demonstrates covariance, and the second assignment demonstrates contravariance.
With the new context keyword out and in , you can specify whether a generic type is to be passed to a delegate or an interface method, or to be returned from a delegate or an interface method.
| 1.b,simplevariance Sample Code back to top |
1.b.1, Program.cs
//Copyright (C) Microsoft Corporation. All rights reserved. //This code is published in compliance with//Microsoft Public License (MS-PL,http://opensource.org/licenses/ms-pl.html) of the terms. //usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespacesimplevariance{classAnimal {}classCat:animal {}classProgram {//to understand what the new covariant and contravariant code can do for you//try adding or removing the content from the following two lines of code: DelegateT func1< outT>(); Delegate voidaction1<inchT>(T a); Static voidMain (string[] args) {FUNC1<Cat> Cat = () =NewCat (); Func1<Animal> Animal =Cat; Action1<Animal> Act1 = (ani) = ={Console.WriteLine (ANI);}; Action1<Cat> CAT1 =Act1; Console.WriteLine (Animal ()); CAT1 (NewCat ()); } }}View Code
1.b.2,
1.b.exe,
SimpleVariance.CatSimpleVariance.Cat Please press any key to continue ...
1.B,
| 1.C, (free Download) back to top |
|
Ylbtech Source: http://ylbtech.cnblogs.com/ This article is copyright to the author and the blog Park, Welcome to reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to the original link, otherwise reserves the right to pursue legal responsibility. |
Ylbtech-languagesamples-simplevariance