Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is wrong with this use of Predicate / CreateDelegate?
    text
    copied!<p>I'm creating a simple code generator with delegates.</p> <p>Why am I getting this error at runtime:</p> <blockquote> <p><strong>Error while binding the target method.</strong></p> </blockquote> <p>on the following code?</p> <p><strong>XAML:</strong></p> <pre><code>&lt;Window x:Class="Parser.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Loaded="Window_Loaded" Title="Parser" Height="600" Width="800"&gt; &lt;TextBox x:Name="Output" VerticalScrollBarVisibility="Visible" Margin="10"/&gt; &lt;/Window&gt; </code></pre> <p><strong>Code-Behind:</strong></p> <pre><code>using System; using System.Collections.Generic; using System.Text; using System.Windows; namespace Parser { public partial class Window1 : Window { private List&lt;string&gt; _fields; public Window1() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { _fields = new List&lt;string&gt; { "CustomerID", "CompanyName", "ContactName", "ContactTitle", "Address", "City", "Region", "PostalCode", "Country", "Phone", "Fax" }; Output.Text += ParseFieldsWithMethod("BuildAssignmentLines"); Output.Text += ParseFieldsWithMethod("BuildEnabledLines"); } private string ParseFieldsWithMethod(string theParseMethod) { Predicate&lt;string&gt; predicate = (Predicate&lt;string&gt;)Delegate.CreateDelegate(typeof(Predicate&lt;string&gt;), typeof(Window1).GetMethod(theParseMethod)); StringBuilder sb = new StringBuilder(); foreach (var field in _fields) { sb.Append(predicate.Invoke(field)); } return sb.ToString(); } public string BuildAssignmentLines(string field) { return String.Format("customer.{0} = Field_{0}.Text;\n", field); } public string BuildEnabledLines(string field) { return String.Format("Field_{0}.IsEnabled = false;\n", field); } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload