How do you declare a Func with an anonymous return type?
Question
I need to be able to do this:
var getHed = () => { // do stuff return new { Property1 = value, Property2 = value2, etc...}; }; var anonymousClass = getHed();
But I get an error which indicates I need to explicitly declare getHed.
How do I declare Func such that T is the anonymous type I am returning?
In case you are curious why I need to do this, it is because I am using 3rd party software that allows customization code, but only within a single method. This can become very difficult to manage. I had the idea that I could use anonymous methods to help keep the procedural code organized. In this case, for it to help, I need a new class, which I cannot define except anonymously.
Answers
As is basically always the case with anonymous types, the solution is to use a generic method, so that you can use method type inference:
public static Func<TResult> DefineFunc<TResult>(Func<TResult> func) { return func; }
You can now write:
var getHed = DefineFunc(() => { // do stuff return new { Property1 = value, Property2 = value2, etc...}; });
原文地址:https://www.2cto.com/kf/201207/139227.html
using System; namespace ConsoleApplication1 { class Program { static T CastByExample<T>(object obj, Func<T> example) { return (T)obj; www.2cto.com } static void f(object p) { var person = CastByExample(p, () => new { Name = "", Age = 0 }); Console.WriteLine("Name={0},Age={1}", person.Name, person.Age); } static void Main(string[] args) { var person = new { Name = "Tom", Age = 25 }; f(person); } } }