My favorites
▼
|
Sign in
gim-projects
Various open source projects by George Mauer
Project Home
Downloads
Wiki
Source
Checkout
Browse
Changes
Source path:
svn
/
presentations
/
CantDanceTheLambda
/
src
/
MemberNameParser.cs
‹r22
r45
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// Author: George Mauer
// Code samples for presentation You Can't Dance the Lambda
// Slide: And More!
// Build a class to provide access to names of class members without ever having to use weakly typed strings
using System;
using NUnit.Framework;
using System.Linq.Expressions;
namespace CantDanceTheLambda {
/// <summary>
/// An extentension method on an actual object to get its member names
/// </summary>
public static partial class ReflectionExtensions {
public static string MemberName<T, R>(this T obj, Expression<Func<T, R>> expr) {
var node = expr.Body as MemberExpression;
if (object.ReferenceEquals(null, node))
throw new InvalidOperationException("Expression must be of member access");
return node.Member.Name;
}
}
/// <summary>
/// If we don't have an actual object we can still refer to its type with this generic static class
/// </summary>
public static class MembersOf<T> {
public static string GetName<R>(Expression<Func<T,R>> expr) {
var node = expr.Body as MemberExpression;
if (object.ReferenceEquals(null, node))
throw new InvalidOperationException("Expression must be of member access");
return node.Member.Name;
}
}
[TestFixture]
public class MemberNameParserTests {
[Test] public void Can_get_property_name_from_instance() {
var a = new Animal(null, null);
Assert.AreEqual("Status", a.MemberName(x => x.Status));
}
[Test] public void Can_get_property_name_from_class() {
Assert.AreEqual("Status", MembersOf<Animal>.GetName(x => x.Status));
}
}
}
Show details
Hide details
Change log
r25
by gmauer on Sep 9, 2009
Diff
Post presentation, modified and commented code
Go to:
...TheLambda/CantDanceTheLambda.sln
.../docs/Can_t_Dance_the_Lambda.odp
.../docs/Can_t_Dance_the_Lambda.ppt
...Lambda/src/ArrayFilterExample.cs
...da/src/CantDanceTheLambda.csproj
...ambda/src/CantDanceTheLambda.sln
...anceTheLambda/src/CustomUsing.cs
...bda/src/DynamicMethodsInTests.cs
...ceTheLambda/src/EventAdapting.cs
...DanceTheLambda/src/EventClass.cs
...bda/src/FluentInterfaceConfig.cs
...da/src/LambdasAreDelegatesToo.cs
...s/CantDanceTheLambda/src/Lazy.cs
...heLambda/src/MemberNameParser.cs
...antDanceTheLambda/src/MyClass.cs
...nceTheLambda/src/StrategyHash.cs
.../StringFilterViaDelegateTests.cs
...tDanceTheLambda/src/Utilities.cs
...ions/CantDanceTheLambda/src/docs
Project members,
sign in
to write a code review
Older revisions
r22
by gmauer on Sep 1, 2009
Diff
[No log message]
All revisions of this file
File info
Size: 1789 bytes, 43 lines
View raw file
Powered by
Google Project Hosting