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); 
            } 
        } 
    } 
     
  • 相关阅读:
    输入输出重定向
    进程管理
    普通变量_环境变量_环境变量配置文件
    高级文件操作命令_文件查找
    软件包管理_rpm命令管理_yum工具管理_文件归档压缩_源码包管理
    用户管理_组管理_设置主机名_UGO_文件高级权限_ACL权限
    字符串是否包含中文
    SQL 优化
    JS数组
    RedisUtil 工具类
  • 原文地址:https://www.cnblogs.com/FH-cnblogs/p/10494111.html
Copyright © 2011-2022 走看看