SlideShare a Scribd company logo
1 of 11
Covariance, Contravariance 觀念分享
                             Howard
Covariance

string[] strings = new string[3];
object[] objects = strings;

// RunTimeError !! 發生 ArrayTypeMismatchException!
objects[0] = DateTime.Now;
string s = (string)objects[0];
Covariance – generic types


List<string> stringList = new List<string>();
List<object> objectList = stringList;

Cannot implicitly convert type 'System.Collections.Generic.List<string>' to
'System.Collections.Generic.List<object>’


泛型本身具有不變性( invariance )
Covariance in .Net 4.0
List<string> stringList = new List<string>();

// C# 2/3 不允許, C# 4.0 OK!
IEnumerable<object> objects = stringList;



WHY ?
Covariance in .Net 4.0
public interface IEnumerable<out T> : Ienumerable
{

     IEnumerator<T> GetEnumerator();
}

型別 T 在這個泛型介面中只能用於 method 的傳回值,而不能用來當
作 method 的參數

public interface IFoo<out T>
{
          // 編譯失敗:型別 T 在這裡只能用於方法的傳回值,不可當
作參數。
          string Convert(T obj);
          T GetInstance();    // OK!
}
Covariance in .Net 4.0
 用 IEnumerable<T> 把一串物件包起來,難道不會跟前面
 的陣列 covariance 範例一樣產生型別安全的問題嗎?

 答案是不會。因為 IEnumerable<T> 的操作都是唯讀的,你無法透
 過它去替換或增刪串列中的元素。
Contravariance
   跟 Covariance 相反 - in

static object GetObject() { return null; }
     static void SetObject(object obj) { }
     static string GetString() { return ""; }
     static void SetString(string str) { }


static void Test()
     {
       // Covariance. A delegate specifies a return type as object,
       // but you can assign a method that returns a string.
       Func<object> del = GetString;

  // Contravariance. A delegate specifies a parameter type as string,
       // but you can assign a method that takes an object.

  Action<string> del2 = SetObject;
    }
Contravariance

public interface MyIComparer<in Tin>
{

       int Compare(Tin left, Tin right);
}
結論
 In .NET Framework 4, both C# and Visual Basic support
  covariance and contravariance in generic interfaces and
  delegates and allow for implicit conversion of generic type
  parameters.
Reference
 C# 4.0 : Covariance 與 Contravariance 觀念入門
   http://huan-lin.blogspot.com/2009/10/c-40covariance-and-
     contravariance.html

 Covariance and Contravariance (C# and Visual Basic)
   http://msdn.microsoft.com/en-us/library/ee207183.aspx
Q&A

More Related Content

What's hot

JavaScript: Patterns, Part 2
JavaScript: Patterns, Part  2JavaScript: Patterns, Part  2
JavaScript: Patterns, Part 2Chris Farrell
 
C# language basics (Visual studio)
C# language basics (Visual studio)C# language basics (Visual studio)
C# language basics (Visual studio)rnkhan
 
Type conversions
Type conversionsType conversions
Type conversionssanya6900
 
Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++Gamindu Udayanga
 
Data Type Conversion in C++
Data Type Conversion in C++Data Type Conversion in C++
Data Type Conversion in C++Danial Mirza
 
Whats to come with swift generics
Whats to come with swift genericsWhats to come with swift generics
Whats to come with swift genericsDenis Poifol
 
#4 (Remote Method Invocation)
#4 (Remote Method Invocation)#4 (Remote Method Invocation)
#4 (Remote Method Invocation)Ghadeer AlHasan
 
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12Abu Saleh
 
Double pointer (pointer to pointer)
Double pointer (pointer to pointer)Double pointer (pointer to pointer)
Double pointer (pointer to pointer)sangrampatil81
 
CallSharp: Automatic Input/Output Matching in .NET
CallSharp: Automatic Input/Output Matching in .NETCallSharp: Automatic Input/Output Matching in .NET
CallSharp: Automatic Input/Output Matching in .NETDmitri Nesteruk
 
Java%20 new%20faq.doc 0
Java%20 new%20faq.doc 0Java%20 new%20faq.doc 0
Java%20 new%20faq.doc 0aravind_aashu
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++gourav kottawar
 
Definitions of Functional Programming
Definitions of Functional ProgrammingDefinitions of Functional Programming
Definitions of Functional ProgrammingPhilip Schwarz
 

What's hot (20)

JavaScript: Patterns, Part 2
JavaScript: Patterns, Part  2JavaScript: Patterns, Part  2
JavaScript: Patterns, Part 2
 
C# language basics (Visual studio)
C# language basics (Visual studio)C# language basics (Visual studio)
C# language basics (Visual studio)
 
Type conversions
Type conversionsType conversions
Type conversions
 
Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++
 
Data Type Conversion in C++
Data Type Conversion in C++Data Type Conversion in C++
Data Type Conversion in C++
 
Whats to come with swift generics
Whats to come with swift genericsWhats to come with swift generics
Whats to come with swift generics
 
16 virtual function
16 virtual function16 virtual function
16 virtual function
 
#4 (Remote Method Invocation)
#4 (Remote Method Invocation)#4 (Remote Method Invocation)
#4 (Remote Method Invocation)
 
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
 
Double pointer (pointer to pointer)
Double pointer (pointer to pointer)Double pointer (pointer to pointer)
Double pointer (pointer to pointer)
 
CallSharp: Automatic Input/Output Matching in .NET
CallSharp: Automatic Input/Output Matching in .NETCallSharp: Automatic Input/Output Matching in .NET
CallSharp: Automatic Input/Output Matching in .NET
 
Java%20 new%20faq.doc 0
Java%20 new%20faq.doc 0Java%20 new%20faq.doc 0
Java%20 new%20faq.doc 0
 
Type Casting in C++
Type Casting in C++Type Casting in C++
Type Casting in C++
 
Pointers
PointersPointers
Pointers
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++
 
Java String
Java String Java String
Java String
 
Definitions of Functional Programming
Definitions of Functional ProgrammingDefinitions of Functional Programming
Definitions of Functional Programming
 
Pointers
PointersPointers
Pointers
 
Typecasting in c
Typecasting in cTypecasting in c
Typecasting in c
 
Function in C++
Function in C++Function in C++
Function in C++
 

Viewers also liked

Strawberries
StrawberriesStrawberries
Strawberriesebanreb07
 
2014's Top 10 Best Carnitine Supplements
2014's Top 10 Best Carnitine Supplements2014's Top 10 Best Carnitine Supplements
2014's Top 10 Best Carnitine SupplementsTop10Supplements.com
 
Choice Art Group Web Transformation Project
Choice Art Group Web Transformation ProjectChoice Art Group Web Transformation Project
Choice Art Group Web Transformation ProjectBenjamin Berman
 
Kees Riekwel - Info battle finalevragen
Kees Riekwel - Info battle finalevragenKees Riekwel - Info battle finalevragen
Kees Riekwel - Info battle finalevragennvbonline
 
Pedagogic implications of wider purpose of HE
Pedagogic implications of wider purpose of HEPedagogic implications of wider purpose of HE
Pedagogic implications of wider purpose of HETansy Jessop
 
Projectphp
ProjectphpProjectphp
Projectphpkneelabh
 
V Игры "Дети Азии" коммуникационный проект
V Игры "Дети Азии"   коммуникационный проектV Игры "Дети Азии"   коммуникационный проект
V Игры "Дети Азии" коммуникационный проектVlad Shulaev
 
50 states assignment
50 states assignment50 states assignment
50 states assignmentmaddycortez
 
214.экономика метод указания по выполнению контрольной работы для студентов з...
214.экономика метод указания по выполнению контрольной работы для студентов з...214.экономика метод указания по выполнению контрольной работы для студентов з...
214.экономика метод указания по выполнению контрольной работы для студентов з...ivanov15666688
 
Vintage Power Boat Racing Program Havasu 1967
Vintage Power Boat Racing Program Havasu 1967Vintage Power Boat Racing Program Havasu 1967
Vintage Power Boat Racing Program Havasu 1967idn12
 
Democratizing Data & Decision-Making: Better Decisions Everywhere
Democratizing Data & Decision-Making: Better Decisions EverywhereDemocratizing Data & Decision-Making: Better Decisions Everywhere
Democratizing Data & Decision-Making: Better Decisions EverywhereBrandwatch
 
Learning Bahasa Indonesia the Easy Way 2
Learning Bahasa Indonesia the Easy Way 2Learning Bahasa Indonesia the Easy Way 2
Learning Bahasa Indonesia the Easy Way 2Sri Suwanti
 
Linked Data and Public Administration
Linked Data and Public AdministrationLinked Data and Public Administration
Linked Data and Public AdministrationOscar Corcho
 

Viewers also liked (18)

Strawberries
StrawberriesStrawberries
Strawberries
 
2014's Top 10 Best Carnitine Supplements
2014's Top 10 Best Carnitine Supplements2014's Top 10 Best Carnitine Supplements
2014's Top 10 Best Carnitine Supplements
 
Choice Art Group Web Transformation Project
Choice Art Group Web Transformation ProjectChoice Art Group Web Transformation Project
Choice Art Group Web Transformation Project
 
Kees Riekwel - Info battle finalevragen
Kees Riekwel - Info battle finalevragenKees Riekwel - Info battle finalevragen
Kees Riekwel - Info battle finalevragen
 
Pedagogic implications of wider purpose of HE
Pedagogic implications of wider purpose of HEPedagogic implications of wider purpose of HE
Pedagogic implications of wider purpose of HE
 
Projectphp
ProjectphpProjectphp
Projectphp
 
V Игры "Дети Азии" коммуникационный проект
V Игры "Дети Азии"   коммуникационный проектV Игры "Дети Азии"   коммуникационный проект
V Игры "Дети Азии" коммуникационный проект
 
50 states assignment
50 states assignment50 states assignment
50 states assignment
 
Sardegna. Artigianato sardo.
Sardegna. Artigianato sardo.Sardegna. Artigianato sardo.
Sardegna. Artigianato sardo.
 
214.экономика метод указания по выполнению контрольной работы для студентов з...
214.экономика метод указания по выполнению контрольной работы для студентов з...214.экономика метод указания по выполнению контрольной работы для студентов з...
214.экономика метод указания по выполнению контрольной работы для студентов з...
 
A multi agent based decision mechanism for incident reaction in telecommunica...
A multi agent based decision mechanism for incident reaction in telecommunica...A multi agent based decision mechanism for incident reaction in telecommunica...
A multi agent based decision mechanism for incident reaction in telecommunica...
 
Social studies
Social studiesSocial studies
Social studies
 
Davies2006
Davies2006Davies2006
Davies2006
 
Lorian Boulevard
Lorian BoulevardLorian Boulevard
Lorian Boulevard
 
Vintage Power Boat Racing Program Havasu 1967
Vintage Power Boat Racing Program Havasu 1967Vintage Power Boat Racing Program Havasu 1967
Vintage Power Boat Racing Program Havasu 1967
 
Democratizing Data & Decision-Making: Better Decisions Everywhere
Democratizing Data & Decision-Making: Better Decisions EverywhereDemocratizing Data & Decision-Making: Better Decisions Everywhere
Democratizing Data & Decision-Making: Better Decisions Everywhere
 
Learning Bahasa Indonesia the Easy Way 2
Learning Bahasa Indonesia the Easy Way 2Learning Bahasa Indonesia the Easy Way 2
Learning Bahasa Indonesia the Easy Way 2
 
Linked Data and Public Administration
Linked Data and Public AdministrationLinked Data and Public Administration
Linked Data and Public Administration
 

Similar to Covariance, contravariance 觀念分享

Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Andrew Petryk
 
Whats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPontoWhats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPontoPaulo Morgado
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2Mohamed Krar
 
devLink - What's New in C# 4?
devLink - What's New in C# 4?devLink - What's New in C# 4?
devLink - What's New in C# 4?Kevin Pilch
 
Share pointtechies linqtosp-andsbs
Share pointtechies linqtosp-andsbsShare pointtechies linqtosp-andsbs
Share pointtechies linqtosp-andsbsShakir Majeed Khan
 
Javase5generics
Javase5genericsJavase5generics
Javase5genericsimypraz
 
Consider this code using the ArrayBag of Section 5.2 and the Locat.docx
Consider this code using the ArrayBag of Section 5.2 and the Locat.docxConsider this code using the ArrayBag of Section 5.2 and the Locat.docx
Consider this code using the ArrayBag of Section 5.2 and the Locat.docxmaxinesmith73660
 
CHAPTER - 3 - JAVA NETWORKING.pptx
CHAPTER - 3 - JAVA NETWORKING.pptxCHAPTER - 3 - JAVA NETWORKING.pptx
CHAPTER - 3 - JAVA NETWORKING.pptxDhrumilSheth3
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & AnswersRatnala Charan kumar
 
vectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptx
vectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptxvectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptx
vectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptxVivekSharma34623
 

Similar to Covariance, contravariance 觀念分享 (20)

Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)
 
Whats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPontoWhats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPonto
 
arrays.pptx
arrays.pptxarrays.pptx
arrays.pptx
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2
 
Understanding linq
Understanding linqUnderstanding linq
Understanding linq
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
 
Advance Java
Advance JavaAdvance Java
Advance Java
 
devLink - What's New in C# 4?
devLink - What's New in C# 4?devLink - What's New in C# 4?
devLink - What's New in C# 4?
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Share pointtechies linqtosp-andsbs
Share pointtechies linqtosp-andsbsShare pointtechies linqtosp-andsbs
Share pointtechies linqtosp-andsbs
 
Javase5generics
Javase5genericsJavase5generics
Javase5generics
 
PostThis
PostThisPostThis
PostThis
 
C# - Part 1
C# - Part 1C# - Part 1
C# - Part 1
 
Consider this code using the ArrayBag of Section 5.2 and the Locat.docx
Consider this code using the ArrayBag of Section 5.2 and the Locat.docxConsider this code using the ArrayBag of Section 5.2 and the Locat.docx
Consider this code using the ArrayBag of Section 5.2 and the Locat.docx
 
Linq intro
Linq introLinq intro
Linq intro
 
CHAPTER - 3 - JAVA NETWORKING.pptx
CHAPTER - 3 - JAVA NETWORKING.pptxCHAPTER - 3 - JAVA NETWORKING.pptx
CHAPTER - 3 - JAVA NETWORKING.pptx
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & Answers
 
vectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptx
vectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptxvectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptx
vectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptx
 

More from LearningTech

More from LearningTech (20)

vim
vimvim
vim
 
PostCss
PostCssPostCss
PostCss
 
ReactJs
ReactJsReactJs
ReactJs
 
Docker
DockerDocker
Docker
 
Semantic ui
Semantic uiSemantic ui
Semantic ui
 
node.js errors
node.js errorsnode.js errors
node.js errors
 
Process control nodejs
Process control nodejsProcess control nodejs
Process control nodejs
 
Expression tree
Expression treeExpression tree
Expression tree
 
SQL 效能調校
SQL 效能調校SQL 效能調校
SQL 效能調校
 
flexbox report
flexbox reportflexbox report
flexbox report
 
Vic weekly learning_20160504
Vic weekly learning_20160504Vic weekly learning_20160504
Vic weekly learning_20160504
 
Reflection &amp; activator
Reflection &amp; activatorReflection &amp; activator
Reflection &amp; activator
 
Peggy markdown
Peggy markdownPeggy markdown
Peggy markdown
 
Node child process
Node child processNode child process
Node child process
 
20160415ken.lee
20160415ken.lee20160415ken.lee
20160415ken.lee
 
Peggy elasticsearch應用
Peggy elasticsearch應用Peggy elasticsearch應用
Peggy elasticsearch應用
 
Expression tree
Expression treeExpression tree
Expression tree
 
Vic weekly learning_20160325
Vic weekly learning_20160325Vic weekly learning_20160325
Vic weekly learning_20160325
 
D3js learning tips
D3js learning tipsD3js learning tips
D3js learning tips
 
git command
git commandgit command
git command
 

Recently uploaded

Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 

Recently uploaded (20)

Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 

Covariance, contravariance 觀念分享

  • 2. Covariance string[] strings = new string[3]; object[] objects = strings; // RunTimeError !! 發生 ArrayTypeMismatchException! objects[0] = DateTime.Now; string s = (string)objects[0];
  • 3. Covariance – generic types List<string> stringList = new List<string>(); List<object> objectList = stringList; Cannot implicitly convert type 'System.Collections.Generic.List<string>' to 'System.Collections.Generic.List<object>’ 泛型本身具有不變性( invariance )
  • 4. Covariance in .Net 4.0 List<string> stringList = new List<string>(); // C# 2/3 不允許, C# 4.0 OK! IEnumerable<object> objects = stringList; WHY ?
  • 5. Covariance in .Net 4.0 public interface IEnumerable<out T> : Ienumerable { IEnumerator<T> GetEnumerator(); } 型別 T 在這個泛型介面中只能用於 method 的傳回值,而不能用來當 作 method 的參數 public interface IFoo<out T> { // 編譯失敗:型別 T 在這裡只能用於方法的傳回值,不可當 作參數。 string Convert(T obj); T GetInstance(); // OK! }
  • 6. Covariance in .Net 4.0  用 IEnumerable<T> 把一串物件包起來,難道不會跟前面 的陣列 covariance 範例一樣產生型別安全的問題嗎? 答案是不會。因為 IEnumerable<T> 的操作都是唯讀的,你無法透 過它去替換或增刪串列中的元素。
  • 7. Contravariance  跟 Covariance 相反 - in static object GetObject() { return null; } static void SetObject(object obj) { } static string GetString() { return ""; } static void SetString(string str) { } static void Test() { // Covariance. A delegate specifies a return type as object, // but you can assign a method that returns a string. Func<object> del = GetString; // Contravariance. A delegate specifies a parameter type as string, // but you can assign a method that takes an object. Action<string> del2 = SetObject; }
  • 8. Contravariance public interface MyIComparer<in Tin> { int Compare(Tin left, Tin right); }
  • 9. 結論  In .NET Framework 4, both C# and Visual Basic support covariance and contravariance in generic interfaces and delegates and allow for implicit conversion of generic type parameters.
  • 10. Reference  C# 4.0 : Covariance 與 Contravariance 觀念入門  http://huan-lin.blogspot.com/2009/10/c-40covariance-and- contravariance.html  Covariance and Contravariance (C# and Visual Basic)  http://msdn.microsoft.com/en-us/library/ee207183.aspx
  • 11. Q&A