SlideShare ist ein Scribd-Unternehmen logo
1 von 70
https://atnd.org/events/57085
• 
• 
• http://blog.shos.info 
• 
•
• 
http://slidesha.re/1tA0Tit 
• 
http://1drv.ms/1zs3n78 
3 
ソースコード 
参照
•
1. 
2. 
3. 
4. 
5.
• 
IEnumerable<int> sequence1 = new[] { 1, 1, 2, 3, 5, 8, 13, 21, 34 }; 
IEnumerable<int> sequence2 = sequence1.Where (x => x % 2 == 0); 
IEnumerable<int> sequence3 = sequence2.Select (x => x * x ); 
foreach (int item in sequence3) 
Console.WriteLine(item); 
ソースコード 
参照
•
• 
ソースコード 
参照 
IEnumerable<int> sequence1 = new[] { 1, 1, 2, 3, 5, 8, 13, 21, 34 }; 
IEnumerable<int> sequence2 = sequence1.Where (x => x % 2 == 0); 
IEnumerable<int> sequence3 = sequence2.Select (x => x * x ); 
foreach (int item in sequence3) 
Console.WriteLine(item); 実際にsequence3 から値が取り出さ 
れるまで、sequence1 から値は取り 
出されず、Where やSelect に渡した 
デリゲートも実行されない
• 
var data = new EmployeeDataClassesDataContext(); 
data.Log = Console.Out; 
var sequence1 = data.Employee; 
var sequence2 = sequence1.Where ( 
ソースコード 
参照 
employee => employee.Name.Contains("田") ); 
var sequence3 = sequence2.Select ( 
employee => new { 番号= employee.Id, 名前= employee.Name }); 
foreach (var employee in sequence3) 
Console.WriteLine("{0}: {1}", employee.番号, employee.名前);
• 
SELECT [t0].[Id], [t0].[Name] 
FROM [dbo].[Employee] AS [t0] 
• 
SELECT [t0].[Id] AS [番号], [t0].[Name] AS [名前] 
FROM [dbo].[Employee] AS [t0] 
WHERE [t0].[Name] LIKE @p0 
-- @p0: Input NVarChar (Size = 4000; Prec = 0; Scale = 0) [%田%]
• 
public static class Enumerable 
{ 
public static class Queryable 
{ 
public static IQueryable<T> Where<T>(this IQueryable<T> source, 
Expression<Func<T, bool>> predicate); 
} 
public static IEnumerable<T> Where<T>(this IEnumerable<T> source, 
Func<T, int, bool> predicate); 
} 
•
• 
• 
•
• 
class Program 
{ 
static void Main() 
{ 
ソースコード 
Func<int, int, int> sequence1 = (x, y) => x + y; 
Func<int, int, int> sequence2 = (x, y) => { return x + y; }; 
Expression<Func<int, int, int>> expression1 = (x, y) => x + y; 
//Expression<Func<int, int, int>> expression2 = (x, y) => 
{ return x + y; }; 
} 
} 
ブロックが含まれるラムダ式は式として扱えない 
(IQueryable<T> には使えない) 
参照
• 
• 
var sequence4 = from employee in data.Employee 
where employee.Name.Contains("田") 
select new { 番号= employee.Id, 
名前= employee.Name };
• 
•
• 
• http://msdn.microsoft.com/ja-jp/library/system.linq.iqueryable(v=vs.110).aspx 
public interface IQueryable : IEnumerable 
{ 
Type ElementType { get; } 
Expression Expression { get; } 
IQueryProvider Provider { get; } 
} 
public interface IQueryable<T> : IEnumerable<T>, IQueryable 
{}
• 
class Foo : IQueryable 
{ 
public Type ElementType 
{ get { throw new NotImplementedException(); } } 
public Expression Expression 
{ get { throw new NotImplementedException(); } } 
public IQueryProvider Provider 
{ get { throw new NotImplementedException(); } } 
public IEnumerator GetEnumerator() 
{ throw new NotImplementedException(); } 
} 
ソースコード 
参照
• 
ソースコード 
参照 
Expression<Func<int, int, int>> expression = (x, y) => x + y; 
((Expression)expression).Show();
•
•
•
•
•
• 
• 
• 
• 
• 
Assembly Module 
Type 
・Class 
・Interface 
・Value Type 
FieldInfo 
PropertyInfo 
EventInfo 
MethodInfo 
ConstructorInfo ParameterInfo
• 
• 
• 
•
• 
• 
•
• 
• 
• 
• 
• 
•
• 
• 
• 
•
• 
• 
• 
CodeDOM CodeDOMProvider 
ソースコード 
(C#、VB、JScript) 
アセンブリ 
GenerateCodeFromNamespace 
CompileAssemblyFromDom
• 
• 
• 
•
• 
namespace CodeDomHelloWorldDemo 
{ 
using System; 
class Program 
{ 
static void Main() 
{ 
Console.WriteLine("Hello world!"); 
Console.ReadKey(); 
} 
} 
} 
ソースコード 
参照
• 
• 
• 
• http://msdn.microsoft.com/ja-jp/library/f7dy01k1(v=vs.110).aspx
• 
•
Expression<Func<Employee, bool>> expression = employee => employee.Name.Contains("山"); 
Parameters 
Body Object 
Method 
Arguments 
Expression 
Member 
employee => 
employee.Name.Con 
tains("山") 
employee.Name 
Contains 
employee 
Name 
“山” 
employee 
employee.Name.Co 
ntains("山")
• 
1. 
2. 
+ 
=> 
x y 
(x, y)
• Expression の派生クラス一覧- 継承階層- Expression クラス- MSDN ライブラリ
パラメーターのx とy は、(x, y) 部分 
とx + y 部分で使われているが、 
それぞれ1 インスタンスずつにする
• 
static Func<int, int, int> AddByExpression() 
{ 
// 生成したい式 
// (int x, int y) => x + y 
// 引数x の式 
var x = Expression.Parameter(type: typeof(int)); 
// 引数y の式 
var y = Expression.Parameter(type: typeof(int)); 
// x + y の式 
var add = Expression.Add (left: x, right: y); 
// (x, y) => x + y の式 
var lambda = Expression.Lambda (add, x, y ); 
// ラムダ式をコンパイルしてデリゲートとして返す 
return (Func<int, int, int>)lambda.Compile(); 
} 
ソースコード 
参照
• 
static Func<int, int, int> AddByExpression() 
{ 
// 生成したい式 
// (int x, int y) => x + y 
// 引数x の式 
var x = Expression.Parameter(type: typeof(int)); 
// 引数y の式 
var y = Expression.Parameter(type: typeof(int)); 
// x + y の式 
var add = Expression.Add (left: x, right: y); 
// (x, y) => x + y の式 
var lambda = Expression.Lambda (add, x, y ); 
// ラムダ式をコンパイルしてデリゲートとして返す 
return (Func<int, int, int>)lambda.Compile(); 
} 
ソースコード 
参照
• 
1. 
2. 
3. 
• 
1. 
2. 
3. 
4.
•
•
• 
// Expression (式) によるメソッド呼び出しメソッドの生成 
static Func<T, TResult> CallByExpression<T, TResult>(string methodName) 
{ 
// 生成したい式の例: 
// (T item) => item.methodName() 
// 引数item の式 
var parameterExpression = Expression.Parameter(type: typeof(T), name: 
"item"); 
// item.methodName() の式 
var callExpression = Expression.Call( 
instance: parameterExpression, 
method : typeof(T).GetMethod(methodName, Type.EmptyTypes) 
); 
// item => item.methodName() の式 
var lambda = Expression.Lambda(callExpression, parameterExpression); 
// ラムダ式をコンパイルしてデリゲートとして返す 
return (Func<T, TResult>)lambda.Compile(); 
} 
ソースコード 
参照
• 
•
• 
1. 
2.
• 
1. 
2. 
1. 
2. 
3. 
1. 
2. 
3. 
4. 
1. 
2. 
3.
•
•
• 
• 
• 
• 
• http://blog.jhashimoto.net/entry/20120616/1339806360
• 
• http://msdn.microsoft.com/ja-jp/library/bb546158.aspx 
• 
• http://blogs.msdn.com/b/mattwar/archive/2008/11/18/linq-links.aspx 
• 
• http://weblogs.asp.net/mehfuzh/writing-custom-linq-provider
LINQプロバイダー 
(IQueryProvider) 
クエリーコンテキスト 
式 
クエリー 
(IQueryable) 
式を解釈
• 
• 
• 
•
• ソースコード 
pubic class QueryProvider : IQueryProvider 
{ 
public IQueryable<TCollection> 
CreateQuery<TCollection>(Expression expression) 
{ return new QueryableData<TCollection>(this, expression); } 
IQueryable IQueryProvider.CreateQuery(Expression expression) 
{ return null; } 
public TResult Execute<TResult>(Expression expression) 
{ return default(TResult); } 
public object Execute(Expression expression) 
{ 
// ここで式木を解釈して、IEnumerable を作って返す 
} 
} 
参照
• 
• 
•
• 
static void Main() 
{ 
IQueryable<int> query1 = new QueryableData<int>(new QueryProvider()); 
Console.WriteLine(query1.Expression); 
IQueryable<int> query2 = query1.Where(x => x % 2 == 0); 
Console.WriteLine(query2.Expression); 
IQueryable<int> query3 = query2.OrderBy(x => x); 
Console.WriteLine(query3.Expression); 
IQueryable<int> query4 = query3.Select(x => x * x); 
Console.WriteLine(query4.Expression); 
foreach (int item in query4) 
Console.WriteLine(item); 
} 
ソースコード 
参照
• 
value(ProviderSample.QueryableData`1[System.Int32]) 
value(ProviderSample.QueryableData`1[System.Int32]).Where(x => ((x % 2) == 0)) 
value(ProviderSample.QueryableData`1[System.Int32]).Where(x => ((x % 2) == 0)).OrderBy(x 
=> x) 
value(ProviderSample.QueryableData`1[System.Int32]).Where(x => ((x % 2) == 0)).OrderBy(x 
=> x).Select(x => (x * x)) 
1 
1 
2 
3 
5 
8 
13 
21 
34
• 
•
• 
public class MyExpressionVisitor : ExpressionVisitor 
{ 
protected override Expression VisitBinary(BinaryExpression expression) 
{ return base.VisitBinary(expression); } 
protected override Expression VisitConstant(ConstantExpression expression) 
{ return base.VisitConstant(expression); } 
protected override Expression VisitMethodCall(MethodCallExpression expression) 
{ return base.VisitMethodCall(expression); } 
protected override Expression VisitParameter(ParameterExpression expression) 
{ return base.VisitParameter(expression); } 
…… 等々…… 
} 
ソースコード 
参照
• 
☆式(x, y) => x + y 
二項演算((x + y)) - 右辺: x, 左辺: y, 型: System.Int32 
引数(x) - 名前: x, 型: System.Int32 
引数(y) - 名前: y, 型: System.Int32 
引数(x) - 名前: x, 型: System.Int32 
引数(y) - 名前: y, 型: System.Int32 
☆式text => text.Contains("福") 
メソッドコール(text.Contains("福")) - メソッド名: Contains, 型: System.Boolean 
引数(text) - 名前: text, 型: System.String 
定数("福") - 値: 福, 型: System.String 
引数(text) - 名前: text, 型: System.String
• 
public class QueryableTimeline<TElement> : IOrderedQueryable<TElement> 
{ 
public IQueryProvider Provider { get; private set; } 
public Expression Expression { get; private set; } 
public Type ElementType 
{ get { return typeof(TElement); } } 
public QueryableTimeline() 
{ 
Provider = new TimelineQueryProvider(); 
Expression = Expression.Constant(this); 
} 
…… 途中省略…… 
} 
ソースコード 
参照
•

Weitere ähnliche Inhalte

Was ist angesagt?

オブジェクト指向できていますか?
オブジェクト指向できていますか?オブジェクト指向できていますか?
オブジェクト指向できていますか?
Moriharu Ohzu
 
日本語テストメソッドについて
日本語テストメソッドについて日本語テストメソッドについて
日本語テストメソッドについて
kumake
 
Constexpr 中3女子テクニック
Constexpr 中3女子テクニックConstexpr 中3女子テクニック
Constexpr 中3女子テクニック
Genya Murakami
 
すごい constexpr たのしくレイトレ!
すごい constexpr たのしくレイトレ!すごい constexpr たのしくレイトレ!
すごい constexpr たのしくレイトレ!
Genya Murakami
 

Was ist angesagt? (20)

C#次世代非同期処理概観 - Task vs Reactive Extensions
C#次世代非同期処理概観 - Task vs Reactive ExtensionsC#次世代非同期処理概観 - Task vs Reactive Extensions
C#次世代非同期処理概観 - Task vs Reactive Extensions
 
関数型プログラミングのデザインパターンひとめぐり
関数型プログラミングのデザインパターンひとめぐり関数型プログラミングのデザインパターンひとめぐり
関数型プログラミングのデザインパターンひとめぐり
 
Visual C++で使えるC++11
Visual C++で使えるC++11Visual C++で使えるC++11
Visual C++で使えるC++11
 
PPL 2022 招待講演: 静的型つき函数型組版処理システムSATySFiの紹介
PPL 2022 招待講演: 静的型つき函数型組版処理システムSATySFiの紹介PPL 2022 招待講演: 静的型つき函数型組版処理システムSATySFiの紹介
PPL 2022 招待講演: 静的型つき函数型組版処理システムSATySFiの紹介
 
オブジェクト指向できていますか?
オブジェクト指向できていますか?オブジェクト指向できていますか?
オブジェクト指向できていますか?
 
日本語テストメソッドについて
日本語テストメソッドについて日本語テストメソッドについて
日本語テストメソッドについて
 
圏論のモナドとHaskellのモナド
圏論のモナドとHaskellのモナド圏論のモナドとHaskellのモナド
圏論のモナドとHaskellのモナド
 
何となく勉強した気分になれるパーサ入門
何となく勉強した気分になれるパーサ入門何となく勉強した気分になれるパーサ入門
何となく勉強した気分になれるパーサ入門
 
例外設計における大罪
例外設計における大罪例外設計における大罪
例外設計における大罪
 
プログラムの処方箋~健康なコードと病んだコード
プログラムの処方箋~健康なコードと病んだコードプログラムの処方箋~健康なコードと病んだコード
プログラムの処方箋~健康なコードと病んだコード
 
ドメイン駆動で開発する ラフスケッチから実装まで
ドメイン駆動で開発する ラフスケッチから実装までドメイン駆動で開発する ラフスケッチから実装まで
ドメイン駆動で開発する ラフスケッチから実装まで
 
C++ マルチスレッド 入門
C++ マルチスレッド 入門C++ マルチスレッド 入門
C++ マルチスレッド 入門
 
継承やめろマジやめろ。 なぜイケないのか 解説する
継承やめろマジやめろ。 なぜイケないのか 解説する継承やめろマジやめろ。 なぜイケないのか 解説する
継承やめろマジやめろ。 なぜイケないのか 解説する
 
Constexpr 中3女子テクニック
Constexpr 中3女子テクニックConstexpr 中3女子テクニック
Constexpr 中3女子テクニック
 
すごい constexpr たのしくレイトレ!
すごい constexpr たのしくレイトレ!すごい constexpr たのしくレイトレ!
すごい constexpr たのしくレイトレ!
 
ワタシはSingletonがキライだ
ワタシはSingletonがキライだワタシはSingletonがキライだ
ワタシはSingletonがキライだ
 
async/await のしくみ
async/await のしくみasync/await のしくみ
async/await のしくみ
 
ホモトピー型理論入門
ホモトピー型理論入門ホモトピー型理論入門
ホモトピー型理論入門
 
最新C++事情 C++14-C++20 (2018年10月)
最新C++事情 C++14-C++20 (2018年10月)最新C++事情 C++14-C++20 (2018年10月)
最新C++事情 C++14-C++20 (2018年10月)
 
オンラインゲームの仕組みと工夫
オンラインゲームの仕組みと工夫オンラインゲームの仕組みと工夫
オンラインゲームの仕組みと工夫
 

Andere mochten auch

Xamarin ~ iOS/Android/Windows アプリを C# で作ろう~
Xamarin ~ iOS/Android/Windows アプリをC# で作ろう~Xamarin ~ iOS/Android/Windows アプリをC# で作ろう~
Xamarin ~ iOS/Android/Windows アプリを C# で作ろう~
Fujio Kojima
 
Bodlogiin code
Bodlogiin codeBodlogiin code
Bodlogiin code
orgil
 

Andere mochten auch (20)

メタプログラミング C#
メタプログラミング C#メタプログラミング C#
メタプログラミング C#
 
C# 6.0 Preview
C# 6.0 PreviewC# 6.0 Preview
C# 6.0 Preview
 
Windows アプリケーション開発 はじめに ~ Windows アプリケーション開発初学者の方向け Visual Studio を使ったアプリケーショ...
Windows アプリケーション開発はじめに ~ Windows アプリケーション開発初学者の方向けVisual Studio を使ったアプリケーショ...Windows アプリケーション開発はじめに ~ Windows アプリケーション開発初学者の方向けVisual Studio を使ったアプリケーショ...
Windows アプリケーション開発 はじめに ~ Windows アプリケーション開発初学者の方向け Visual Studio を使ったアプリケーショ...
 
C# 3.0 以降
C# 3.0 以降C# 3.0 以降
C# 3.0 以降
 
.NET MVP によるドキドキ・ライブコーディング! 小島の分
.NET MVP によるドキドキ・ライブコーディング! 小島の分.NET MVP によるドキドキ・ライブコーディング! 小島の分
.NET MVP によるドキドキ・ライブコーディング! 小島の分
 
Xamarin ~ iOS/Android/Windows アプリを C# で作ろう~
Xamarin ~ iOS/Android/Windows アプリをC# で作ろう~Xamarin ~ iOS/Android/Windows アプリをC# で作ろう~
Xamarin ~ iOS/Android/Windows アプリを C# で作ろう~
 
C# MVP に聞くC#アレコレ! 小島の分
C# MVP に聞くC#アレコレ! 小島の分C# MVP に聞くC#アレコレ! 小島の分
C# MVP に聞くC#アレコレ! 小島の分
 
Windows 8 ストア アプリ 開発 Tips
Windows 8 ストア アプリ 開発 TipsWindows 8 ストア アプリ 開発 Tips
Windows 8 ストア アプリ 開発 Tips
 
3D で遊ぼう ~C#er も TypeScript で楽々 WebGL~
3D で遊ぼう ~C#er も TypeScript で楽々 WebGL~3D で遊ぼう ~C#er も TypeScript で楽々 WebGL~
3D で遊ぼう ~C#er も TypeScript で楽々 WebGL~
 
Final LINQ Extensions II
Final LINQ Extensions IIFinal LINQ Extensions II
Final LINQ Extensions II
 
Final LINQ Extensions
Final LINQ ExtensionsFinal LINQ Extensions
Final LINQ Extensions
 
式の体を成して無い式を式の体を成すように式と式木で何とかする式
式の体を成して無い式を式の体を成すように式と式木で何とかする式式の体を成して無い式を式の体を成すように式と式木で何とかする式
式の体を成して無い式を式の体を成すように式と式木で何とかする式
 
よろしい、ならばMicro-ORMだ
よろしい、ならばMicro-ORMだよろしい、ならばMicro-ORMだ
よろしい、ならばMicro-ORMだ
 
Windows phoneの開発ツール
Windows phoneの開発ツールWindows phoneの開発ツール
Windows phoneの開発ツール
 
Bodlogiin code
Bodlogiin codeBodlogiin code
Bodlogiin code
 
2014 08-30 life with roslyn
2014 08-30 life with roslyn2014 08-30 life with roslyn
2014 08-30 life with roslyn
 
Visual Studio 2017 RC C# まわり
Visual Studio 2017 RC C# まわりVisual Studio 2017 RC C# まわり
Visual Studio 2017 RC C# まわり
 
Final LINQ extensions III
Final LINQ extensions IIIFinal LINQ extensions III
Final LINQ extensions III
 
ADO.NETとORMとMicro-ORM -dapper dot netを使ってみた
ADO.NETとORMとMicro-ORM -dapper dot netを使ってみたADO.NETとORMとMicro-ORM -dapper dot netを使ってみた
ADO.NETとORMとMicro-ORM -dapper dot netを使ってみた
 
You will be assimilated. Resistance is futile.
You will be assimilated. Resistance is futile.You will be assimilated. Resistance is futile.
You will be assimilated. Resistance is futile.
 

Ähnlich wie C# 式木 (Expression Tree) ~ LINQをより深く理解するために ~

Replace Output Iterator and Extend Range JP
Replace Output Iterator and Extend Range JPReplace Output Iterator and Extend Range JP
Replace Output Iterator and Extend Range JP
Akira Takahashi
 
知って得するC#
知って得するC#知って得するC#
知って得するC#
Shota Baba
 

Ähnlich wie C# 式木 (Expression Tree) ~ LINQをより深く理解するために ~ (20)

C# LINQ ~深く知って、使いまくろう~
C# LINQ ~深く知って、使いまくろう~C# LINQ ~深く知って、使いまくろう~
C# LINQ ~深く知って、使いまくろう~
 
Replace Output Iterator and Extend Range JP
Replace Output Iterator and Extend Range JPReplace Output Iterator and Extend Range JP
Replace Output Iterator and Extend Range JP
 
asm.js x emscripten: The foundation of the next level Web games
asm.js x emscripten: The foundation of the next level Web gamesasm.js x emscripten: The foundation of the next level Web games
asm.js x emscripten: The foundation of the next level Web games
 
C++0x 言語の未来を語る
C++0x 言語の未来を語るC++0x 言語の未来を語る
C++0x 言語の未来を語る
 
10分で分かるr言語入門ver2.10 14 1101
10分で分かるr言語入門ver2.10 14 110110分で分かるr言語入門ver2.10 14 1101
10分で分かるr言語入門ver2.10 14 1101
 
C#勉強会 ~ C#9の新機能 ~
C#勉強会 ~ C#9の新機能 ~C#勉強会 ~ C#9の新機能 ~
C#勉強会 ~ C#9の新機能 ~
 
Project lambda
Project lambdaProject lambda
Project lambda
 
知って得するC#
知って得するC#知って得するC#
知って得するC#
 
Introduction of Python
Introduction of PythonIntroduction of Python
Introduction of Python
 
10分で分かるr言語入門ver2.9 14 0920
10分で分かるr言語入門ver2.9 14 0920 10分で分かるr言語入門ver2.9 14 0920
10分で分かるr言語入門ver2.9 14 0920
 
Teclab3
Teclab3Teclab3
Teclab3
 
【LT版】Elixir入門「第7回:Python/KerasをElixirから繋いでアレコレする」
【LT版】Elixir入門「第7回:Python/KerasをElixirから繋いでアレコレする」【LT版】Elixir入門「第7回:Python/KerasをElixirから繋いでアレコレする」
【LT版】Elixir入門「第7回:Python/KerasをElixirから繋いでアレコレする」
 
中3女子が狂える本当に気持ちのいい constexpr
中3女子が狂える本当に気持ちのいい constexpr中3女子が狂える本当に気持ちのいい constexpr
中3女子が狂える本当に気持ちのいい constexpr
 
Scala with DDD
Scala with DDDScala with DDD
Scala with DDD
 
研究生のためのC++ no.2
研究生のためのC++ no.2研究生のためのC++ no.2
研究生のためのC++ no.2
 
J qmobiはjqueryから軽量化しているか
J qmobiはjqueryから軽量化しているかJ qmobiはjqueryから軽量化しているか
J qmobiはjqueryから軽量化しているか
 
[東京] JapanSharePointGroup 勉強会 #2
[東京] JapanSharePointGroup 勉強会 #2[東京] JapanSharePointGroup 勉強会 #2
[東京] JapanSharePointGroup 勉強会 #2
 
Boost tour 1_40_0
Boost tour 1_40_0Boost tour 1_40_0
Boost tour 1_40_0
 
Boost Tour 1.50.0 All
Boost Tour 1.50.0 AllBoost Tour 1.50.0 All
Boost Tour 1.50.0 All
 
Ajax 応用
Ajax 応用Ajax 応用
Ajax 応用
 

Mehr von Fujio Kojima

.NET 5 勉強会 ~.NET Framework から .NET へ~
.NET 5 勉強会 ~.NET Framework から .NET へ~.NET 5 勉強会 ~.NET Framework から .NET へ~
.NET 5 勉強会 ~.NET Framework から .NET へ~
Fujio Kojima
 

Mehr von Fujio Kojima (20)

Burikaigi 2023「C# Live Coding!」 小島の分
Burikaigi  2023「C# Live Coding!」 小島の分Burikaigi  2023「C# Live Coding!」 小島の分
Burikaigi 2023「C# Live Coding!」 小島の分
 
2022.04.23 .NET 6 -7 時代のデスクトップ アプリケーション開発
2022.04.23 .NET 6 -7 時代のデスクトップ アプリケーション開発2022.04.23 .NET 6 -7 時代のデスクトップ アプリケーション開発
2022.04.23 .NET 6 -7 時代のデスクトップ アプリケーション開発
 
.NET 6 時代のデスクトップ アプリケーション開発
.NET 6 時代のデスクトップ アプリケーション開発.NET 6 時代のデスクトップ アプリケーション開発
.NET 6 時代のデスクトップ アプリケーション開発
 
BuriKaigi 2022 「C# Live Coding!」 小島の分
BuriKaigi 2022 「C# Live Coding!」 小島の分BuriKaigi 2022 「C# Live Coding!」 小島の分
BuriKaigi 2022 「C# Live Coding!」 小島の分
 
.NET 5 勉強会 ~.NET Framework から .NET へ~
.NET 5 勉強会 ~.NET Framework から .NET へ~.NET 5 勉強会 ~.NET Framework から .NET へ~
.NET 5 勉強会 ~.NET Framework から .NET へ~
 
.NETラボ 勉強会 2021年1月 「C#で機械学習」
.NETラボ 勉強会 2021年1月 「C#で機械学習」.NETラボ 勉強会 2021年1月 「C#で機械学習」
.NETラボ 勉強会 2021年1月 「C#で機械学習」
 
『議論パターン』 (Discussion Patterns) ~不毛な議論を避け、実り有る議論とするために~
『議論パターン』 (Discussion Patterns) ~不毛な議論を避け、実り有る議論とするために~『議論パターン』 (Discussion Patterns) ~不毛な議論を避け、実り有る議論とするために~
『議論パターン』 (Discussion Patterns) ~不毛な議論を避け、実り有る議論とするために~
 
C#の新機能勉強会 ~ C#7、8の新機能を活用して速く安全なプログラムを書こう~
C#の新機能勉強会 ~ C#7、8の新機能を活用して速く安全なプログラムを書こう~C#の新機能勉強会 ~ C#7、8の新機能を活用して速く安全なプログラムを書こう~
C#の新機能勉強会 ~ C#7、8の新機能を活用して速く安全なプログラムを書こう~
 
C# ドキドキ ライブ コーディング!! ~ 小島の分 ~ | BuriKaigi 2020
C# ドキドキ ライブ コーディング!! ~ 小島の分 ~ | BuriKaigi 2020C# ドキドキ ライブ コーディング!! ~ 小島の分 ~ | BuriKaigi 2020
C# ドキドキ ライブ コーディング!! ~ 小島の分 ~ | BuriKaigi 2020
 
牛タン会議 2019 @ 仙台 「C# ドキドキ ライブ!!」 小島の分
牛タン会議 2019 @ 仙台 「C# ドキドキ ライブ!!」 小島の分牛タン会議 2019 @ 仙台 「C# ドキドキ ライブ!!」 小島の分
牛タン会議 2019 @ 仙台 「C# ドキドキ ライブ!!」 小島の分
 
『機械学習 (AI/ML) の基礎と Microsoft の AI | 2019/04/02 Global AI Nights Fukui
『機械学習 (AI/ML) の基礎と Microsoft の AI | 2019/04/02 Global AI Nights Fukui『機械学習 (AI/ML) の基礎と Microsoft の AI | 2019/04/02 Global AI Nights Fukui
『機械学習 (AI/ML) の基礎と Microsoft の AI | 2019/04/02 Global AI Nights Fukui
 
機械学習 (AI/ML) 勉強会 #2 IoT編
機械学習 (AI/ML) 勉強会 #2 IoT編 機械学習 (AI/ML) 勉強会 #2 IoT編
機械学習 (AI/ML) 勉強会 #2 IoT編
 
機械学習 (AI/ML) 勉強会 #1 基本編
機械学習 (AI/ML) 勉強会 #1 基本編機械学習 (AI/ML) 勉強会 #1 基本編
機械学習 (AI/ML) 勉強会 #1 基本編
 
BuriKaigi2019 「C# ドキドキ・ライブコーディング」 小島の分
BuriKaigi2019 「C# ドキドキ・ライブコーディング」 小島の分BuriKaigi2019 「C# ドキドキ・ライブコーディング」 小島の分
BuriKaigi2019 「C# ドキドキ・ライブコーディング」 小島の分
 
機械学習入門
機械学習入門機械学習入門
機械学習入門
 
C# でニューラルネットワークをスクラッチで書いて機械学習の原理を理解しよう
C# でニューラルネットワークをスクラッチで書いて機械学習の原理を理解しようC# でニューラルネットワークをスクラッチで書いて機械学習の原理を理解しよう
C# でニューラルネットワークをスクラッチで書いて機械学習の原理を理解しよう
 
「ふくいソフトウェアコンペティション 2014 大賞受賞者プレゼンテーション」
「ふくいソフトウェアコンペティション 2014 大賞受賞者プレゼンテーション」「ふくいソフトウェアコンペティション 2014 大賞受賞者プレゼンテーション」
「ふくいソフトウェアコンペティション 2014 大賞受賞者プレゼンテーション」
 
HTML5 on ASP.NET
HTML5 on ASP.NETHTML5 on ASP.NET
HTML5 on ASP.NET
 
最新C#動向と関数型言語haskell ~命令型静的プログラミングから関数型動的プログラミングへのシフト~
最新C#動向と関数型言語haskell ~命令型静的プログラミングから関数型動的プログラミングへのシフト~最新C#動向と関数型言語haskell ~命令型静的プログラミングから関数型動的プログラミングへのシフト~
最新C#動向と関数型言語haskell ~命令型静的プログラミングから関数型動的プログラミングへのシフト~
 
Microsoft .NET 入門
Microsoft .NET 入門Microsoft .NET 入門
Microsoft .NET 入門
 

C# 式木 (Expression Tree) ~ LINQをより深く理解するために ~

  • 2. • • • http://blog.shos.info • •
  • 3. • http://slidesha.re/1tA0Tit • http://1drv.ms/1zs3n78 3 ソースコード 参照
  • 4.
  • 5. 1. 2. 3. 4. 5.
  • 6.
  • 7. • IEnumerable<int> sequence1 = new[] { 1, 1, 2, 3, 5, 8, 13, 21, 34 }; IEnumerable<int> sequence2 = sequence1.Where (x => x % 2 == 0); IEnumerable<int> sequence3 = sequence2.Select (x => x * x ); foreach (int item in sequence3) Console.WriteLine(item); ソースコード 参照
  • 8.
  • 9. • ソースコード 参照 IEnumerable<int> sequence1 = new[] { 1, 1, 2, 3, 5, 8, 13, 21, 34 }; IEnumerable<int> sequence2 = sequence1.Where (x => x % 2 == 0); IEnumerable<int> sequence3 = sequence2.Select (x => x * x ); foreach (int item in sequence3) Console.WriteLine(item); 実際にsequence3 から値が取り出さ れるまで、sequence1 から値は取り 出されず、Where やSelect に渡した デリゲートも実行されない
  • 10.
  • 11. • var data = new EmployeeDataClassesDataContext(); data.Log = Console.Out; var sequence1 = data.Employee; var sequence2 = sequence1.Where ( ソースコード 参照 employee => employee.Name.Contains("田") ); var sequence3 = sequence2.Select ( employee => new { 番号= employee.Id, 名前= employee.Name }); foreach (var employee in sequence3) Console.WriteLine("{0}: {1}", employee.番号, employee.名前);
  • 12. • SELECT [t0].[Id], [t0].[Name] FROM [dbo].[Employee] AS [t0] • SELECT [t0].[Id] AS [番号], [t0].[Name] AS [名前] FROM [dbo].[Employee] AS [t0] WHERE [t0].[Name] LIKE @p0 -- @p0: Input NVarChar (Size = 4000; Prec = 0; Scale = 0) [%田%]
  • 13. • public static class Enumerable { public static class Queryable { public static IQueryable<T> Where<T>(this IQueryable<T> source, Expression<Func<T, bool>> predicate); } public static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, int, bool> predicate); } •
  • 15. • class Program { static void Main() { ソースコード Func<int, int, int> sequence1 = (x, y) => x + y; Func<int, int, int> sequence2 = (x, y) => { return x + y; }; Expression<Func<int, int, int>> expression1 = (x, y) => x + y; //Expression<Func<int, int, int>> expression2 = (x, y) => { return x + y; }; } } ブロックが含まれるラムダ式は式として扱えない (IQueryable<T> には使えない) 参照
  • 16. • • var sequence4 = from employee in data.Employee where employee.Name.Contains("田") select new { 番号= employee.Id, 名前= employee.Name };
  • 18. • • http://msdn.microsoft.com/ja-jp/library/system.linq.iqueryable(v=vs.110).aspx public interface IQueryable : IEnumerable { Type ElementType { get; } Expression Expression { get; } IQueryProvider Provider { get; } } public interface IQueryable<T> : IEnumerable<T>, IQueryable {}
  • 19. • class Foo : IQueryable { public Type ElementType { get { throw new NotImplementedException(); } } public Expression Expression { get { throw new NotImplementedException(); } } public IQueryProvider Provider { get { throw new NotImplementedException(); } } public IEnumerator GetEnumerator() { throw new NotImplementedException(); } } ソースコード 参照
  • 20.
  • 21. • ソースコード 参照 Expression<Func<int, int, int>> expression = (x, y) => x + y; ((Expression)expression).Show();
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28. • • • • • Assembly Module Type ・Class ・Interface ・Value Type FieldInfo PropertyInfo EventInfo MethodInfo ConstructorInfo ParameterInfo
  • 29.
  • 30. • • •
  • 32. • • • • • •
  • 33. • • •
  • 34.
  • 35. • • • CodeDOM CodeDOMProvider ソースコード (C#、VB、JScript) アセンブリ GenerateCodeFromNamespace CompileAssemblyFromDom
  • 36. • • •
  • 37. • namespace CodeDomHelloWorldDemo { using System; class Program { static void Main() { Console.WriteLine("Hello world!"); Console.ReadKey(); } } } ソースコード 参照
  • 38. • • • • http://msdn.microsoft.com/ja-jp/library/f7dy01k1(v=vs.110).aspx
  • 40. Expression<Func<Employee, bool>> expression = employee => employee.Name.Contains("山"); Parameters Body Object Method Arguments Expression Member employee => employee.Name.Con tains("山") employee.Name Contains employee Name “山” employee employee.Name.Co ntains("山")
  • 41.
  • 42. • 1. 2. + => x y (x, y)
  • 43. • Expression の派生クラス一覧- 継承階層- Expression クラス- MSDN ライブラリ
  • 44. パラメーターのx とy は、(x, y) 部分 とx + y 部分で使われているが、 それぞれ1 インスタンスずつにする
  • 45. • static Func<int, int, int> AddByExpression() { // 生成したい式 // (int x, int y) => x + y // 引数x の式 var x = Expression.Parameter(type: typeof(int)); // 引数y の式 var y = Expression.Parameter(type: typeof(int)); // x + y の式 var add = Expression.Add (left: x, right: y); // (x, y) => x + y の式 var lambda = Expression.Lambda (add, x, y ); // ラムダ式をコンパイルしてデリゲートとして返す return (Func<int, int, int>)lambda.Compile(); } ソースコード 参照
  • 46. • static Func<int, int, int> AddByExpression() { // 生成したい式 // (int x, int y) => x + y // 引数x の式 var x = Expression.Parameter(type: typeof(int)); // 引数y の式 var y = Expression.Parameter(type: typeof(int)); // x + y の式 var add = Expression.Add (left: x, right: y); // (x, y) => x + y の式 var lambda = Expression.Lambda (add, x, y ); // ラムダ式をコンパイルしてデリゲートとして返す return (Func<int, int, int>)lambda.Compile(); } ソースコード 参照
  • 47. • 1. 2. 3. • 1. 2. 3. 4.
  • 48.
  • 49.
  • 50. • // Expression (式) によるメソッド呼び出しメソッドの生成 static Func<T, TResult> CallByExpression<T, TResult>(string methodName) { // 生成したい式の例: // (T item) => item.methodName() // 引数item の式 var parameterExpression = Expression.Parameter(type: typeof(T), name: "item"); // item.methodName() の式 var callExpression = Expression.Call( instance: parameterExpression, method : typeof(T).GetMethod(methodName, Type.EmptyTypes) ); // item => item.methodName() の式 var lambda = Expression.Lambda(callExpression, parameterExpression); // ラムダ式をコンパイルしてデリゲートとして返す return (Func<T, TResult>)lambda.Compile(); } ソースコード 参照
  • 53. • 1. 2. 1. 2. 3. 1. 2. 3. 4. 1. 2. 3.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58. • • • • • http://blog.jhashimoto.net/entry/20120616/1339806360
  • 59. • • http://msdn.microsoft.com/ja-jp/library/bb546158.aspx • • http://blogs.msdn.com/b/mattwar/archive/2008/11/18/linq-links.aspx • • http://weblogs.asp.net/mehfuzh/writing-custom-linq-provider
  • 61. • • •
  • 62. • ソースコード pubic class QueryProvider : IQueryProvider { public IQueryable<TCollection> CreateQuery<TCollection>(Expression expression) { return new QueryableData<TCollection>(this, expression); } IQueryable IQueryProvider.CreateQuery(Expression expression) { return null; } public TResult Execute<TResult>(Expression expression) { return default(TResult); } public object Execute(Expression expression) { // ここで式木を解釈して、IEnumerable を作って返す } } 参照
  • 64. • static void Main() { IQueryable<int> query1 = new QueryableData<int>(new QueryProvider()); Console.WriteLine(query1.Expression); IQueryable<int> query2 = query1.Where(x => x % 2 == 0); Console.WriteLine(query2.Expression); IQueryable<int> query3 = query2.OrderBy(x => x); Console.WriteLine(query3.Expression); IQueryable<int> query4 = query3.Select(x => x * x); Console.WriteLine(query4.Expression); foreach (int item in query4) Console.WriteLine(item); } ソースコード 参照
  • 65. • value(ProviderSample.QueryableData`1[System.Int32]) value(ProviderSample.QueryableData`1[System.Int32]).Where(x => ((x % 2) == 0)) value(ProviderSample.QueryableData`1[System.Int32]).Where(x => ((x % 2) == 0)).OrderBy(x => x) value(ProviderSample.QueryableData`1[System.Int32]).Where(x => ((x % 2) == 0)).OrderBy(x => x).Select(x => (x * x)) 1 1 2 3 5 8 13 21 34
  • 67. • public class MyExpressionVisitor : ExpressionVisitor { protected override Expression VisitBinary(BinaryExpression expression) { return base.VisitBinary(expression); } protected override Expression VisitConstant(ConstantExpression expression) { return base.VisitConstant(expression); } protected override Expression VisitMethodCall(MethodCallExpression expression) { return base.VisitMethodCall(expression); } protected override Expression VisitParameter(ParameterExpression expression) { return base.VisitParameter(expression); } …… 等々…… } ソースコード 参照
  • 68. • ☆式(x, y) => x + y 二項演算((x + y)) - 右辺: x, 左辺: y, 型: System.Int32 引数(x) - 名前: x, 型: System.Int32 引数(y) - 名前: y, 型: System.Int32 引数(x) - 名前: x, 型: System.Int32 引数(y) - 名前: y, 型: System.Int32 ☆式text => text.Contains("福") メソッドコール(text.Contains("福")) - メソッド名: Contains, 型: System.Boolean 引数(text) - 名前: text, 型: System.String 定数("福") - 値: 福, 型: System.String 引数(text) - 名前: text, 型: System.String
  • 69. • public class QueryableTimeline<TElement> : IOrderedQueryable<TElement> { public IQueryProvider Provider { get; private set; } public Expression Expression { get; private set; } public Type ElementType { get { return typeof(TElement); } } public QueryableTimeline() { Provider = new TimelineQueryProvider(); Expression = Expression.Constant(this); } …… 途中省略…… } ソースコード 参照
  • 70.