Is it possible to pass interpolated strings as parameter to a method?

前端 未结 4 498
一整个雨季
一整个雨季 2021-01-04 13:33

I have started to use Interpolated Strings (new feature of C# 6) and it is really useful and gracefully. But according to my needs I have to pass format of string to a metho

4条回答
  •  伪装坚强ぢ
    2021-01-04 14:03

    Several years since this was asked however I came across this via Google while searching for an answer that I already had in my head, but couldn't get my mind around the implementation/syntax.

    My solution is further to what @Kobi supplied...

    public class Person
        {
            public int Id {get; set;}
            public DateTime DoB {get;set;}
            public String Name {get;set;}
        }
    
    public class MyResolver
    {
        public Func Resolve {get;set;}
        public string ResolveToString(T r) where T : Person
        {
            return this.Resolve(r);
        }
    }
    
    // code to use here...
    var employee = new Person();
    employee.Id = 1234;
    employee.Name = "John";
    employee.DoB = new DateTime(1977,1,1);
    
    var resolver = new MyResolver();
    resolver.Resolve = x => $"This person is called {x.Name}, DoB is {x.DoB.ToString()} and their Id is {x.Id}";
    
    Console.WriteLine(resolver.ResolveToString(employee));
    

    I haven't tested the above for syntax errors but hopefully you get the idea and you can now just define "how" you want the string to look but leave the blanks to be filled in at runtime depending upon the values in your Person object.

    Cheers,

    Wayne

提交回复
热议问题