SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Tendances

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
 

Tendances (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++
 

En vedette

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
 

En vedette (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
 

Similaire à 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
 

Similaire à 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
 

Plus de LearningTech

Plus de 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
 

Dernier

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
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
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
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
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
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
 
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
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 

Dernier (20)

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
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
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
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
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
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
 
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
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 

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