使用保留字(类型名称)作为ExpandoObject或动态属性

时间:2017-04-27 09:37:50

标签: c# asp.net elasticsearch dynamic expandoobject

如何使用保留字的键设置ExpandoObject的属性?

像这样:

 <div class="row">
            <asp:Image ID="guitar" runat="server" Height="187px" 
                ImageUrl="~/images/drum.jpg" Width="239px" />
            <div class="col-md-offset-5">
                     <h2>HEADING</h2>

                    <p>testtetstesttetstesttetstesttetstesttets
                        <br>ftesttetstesttetstesttets
                        <br>testtetstesttetstesttetstesttetstesttets
                        <br>testtetstesttetstesttets
                        <br>testtetstesttetstesttetstesttets.</p>
                    <p><a href="#" class="btn btn-primary" role="button">More..</a>
                    </p>

            </div>
        </div>

1 个答案:

答案 0 :(得分:2)

ExpandoObject中,您可以使用任何字符串值作为属性名称(包括保留字,空格等,甚至空字符串),方法是将ExpandoObject实例强制转换为IDictionary<string, object>

dynamic query = new ExpandoObject();
(query as IDictionary<string, object>)["bool"] = true;
(query as IDictionary<string, object>)[" b o o (g)? l \"e:)\""] = false;
(query as IDictionary<string, object>)[""] = true;

您无法使用&#34;普通C#语法&#34;来访问这些属性(即obj.prop)。您必须将对象强制转换为IDictionary<string, object>并使用索引器访问它们:

var qDict = query as IDictionary<string, object>;
Console.WriteLine(qDict["bool"]);
Console.WriteLine(qDict[" b o o (g)? l \"e:)\""]);
Console.WriteLine(qDict[""]);
// Prints:
//   True
//   False
//   True