zoukankan      html  css  js  c++  java
  • 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); 
            } 
        } 
    } 
     
  • 相关阅读:
    跨数据库操作
    Windows 服务
    Linq To DataTable
    嵌入式软件应用程序开发框架浅见
    31.获取当前系统时间
    30 System类
    29. StringBuilder
    28. string类中方法练习
    27 string类中常用的方法列表
    26.String类(1)
  • 原文地址:https://www.cnblogs.com/FH-cnblogs/p/10494111.html
Copyright © 2011-2022 走看看