简体   繁体   English

如何在C#中将var传递给函数

[英]How to pass var to function in C#

How I can pass var to function? 我怎样才能将var传递给函数?

I need to create the following unknown data model, and pass it to my function, which shout parse it using RazorRenderer: 我需要创建以下未知数据模型,并将其传递给我的函数,该函数使用RazorRenderer喊解析它:

var emailData = new {name="value" , name2="value2" ... , nameN="valueN"}

The function can't receive var, so we used object, but then we can't convert it back, and we get an exception when call: 该函数无法接收var,因此我们使用了object,但是随后无法将其转换回去,因此在调用时会出现异常:

string htmlBody = render.Parse(File.ReadAllText(TemplatePath), emailData );

When I do the following, in same function it works: 当我执行以下操作时,它在相同的功能中起作用:

var emailData = new { UserRequest = "hello", UserEmail = "name@domain.com" };
string htmlBody = render.Parse(File.ReadAllText(TemplatePath), emailData);

But when try to pass the emailData to the function it not work, any idea? 但是,当尝试将emailData传递给该函数不起作用时,有什么主意吗?

I can do the rendering out of the function and pass the result to the function, but I thought it may be nice to do it internally inside the function. 我可以从函数中进行渲染,然后将结果传递给函数,但是我认为在函数内部内部进行渲染可能会很好。

BTW- I tried JSON Serialize and Decerialize, with no luck. 顺便说一句,我尝试了JSON序列化和反序列化,但是没有运气。

If I understand your question correctly, it is not possible. 如果我正确理解您的问题,那是不可能的。 Anonymous type names cannot be represented in user code hence there is no way to make them an input parameter to a function. 匿名类型名称无法在用户代码中表示,因此无法将其设为函数的输入参数。

Your best bet is to create a type and use that as the return from the query and then pass it into the function. 最好的选择是创建一个类型并将其用作查询的返回值,然后将其传递给函数。 For example, 例如,

class YourDataClass {
  public string ColumnName; 
}

var query = (from name in some.Table
            select new YourDataClass { ColumnName = name });
YourMethod(query);

... ...

YourMethod(IEnumerable<YourData> enumerable);

In this case though, you are only selecting a single field, so it may be easier to just select the field directly. 不过,在这种情况下,您仅选择一个字段,因此直接选择该字段可能会更容易。 This will cause the query to be typed as an IEnumerable of the field type. 这将导致查询被键入为字段类型的IEnumerable。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM