• Func 参数或返回 匿名类 anonymous


    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); 
            } 
        } 
    } 
     
  • 相关阅读:
    hdu4578线段树维护平方和,立方和(加,乘,赋值)或者珂朵莉树
    珂朵莉树(ODT老司机树)
    Codeforces Round #524 (Div. 2)D
    HDU1402 FFT高精度乘法模板题
    中国剩余定理poj1006
    POJ
    Install and Config MySQL 8 on Ubuntu
    Protobuf Examples
    Learning Thrift
    Flask Quickstart
  • 原文地址:https://www.cnblogs.com/FH-cnblogs/p/10494111.html
Copyright © 2020-2023  润新知