Передайте универсальный делегат как параметр метода в C # - PullRequest
1 голос
/ 28 ноября 2010

У меня есть декларация делегата:

public delegate IEnumerable<T> SearchInputTextStrategy<T, U>(string param);

Предположим, я создал новый делегат SearchInputTextStrategy и назову его MyDelegate.

это мое объявление метода:

public void BindElements<T, TDisplayProperty,TSortProperty>
(
       IEnumerable<T> dataObjects,
       Func<T, TDisplayProperty> selectorDisplayMember,
       Func<T, TSortProperty> selectorSortMember,
       string delimiter,
       // 1.) how to declare the delegate here as parameter ??
)
{
    // pass here the delegate to a private field to save it
    // 2.) how can I do that?

}

Как мне сделать 1.) и 2.)? : -)

ОБНОВЛЕНИЕ 2:

Хорошо, это то, что я сделал до сих пор:

public class SearchProvider<T>
    {
        public delegate IEnumerable<T> SearchInputTextStrategy<T>(string param);    

        public SearchInputTextStrategy<T> SearchStrategy { get; set; }

        public T TypedValue
        {
            get
            {
                return (T)Convert.ChangeType(SearchStrategy, typeof(T));
            }
        }
    }

UserControl:

 public delegate IEnumerable<T> SearchInputTextStrategy<T>(string param);

 public void BindElements<T, TDisplayProperty,TSortProperty>
        (
            IEnumerable<T> dataObjects,
            Func<T, TDisplayProperty> selectorDisplayMember,
            Func<T, TSortProperty> selectorSortMember,
            string delimiter,
            SearchInputTextStrategy<T> searchStrategy
        )
        { 
               /// assign the searchStrategy to the SearchProvider class 
            var sp = new SearchProvider<T>();
                sp.SearchStrategy = searchStrategy  // DOES NOT WORK !!!     
        }

Пожалуйста, прочтите также мои комментарии в Кодексе. Чего я хочу добиться, так это передать делегата searchProvider, чтобы сохранить его где-нибудь ... Код, который я здесь пишу, я понимаю до 50%, поэтому, пожалуйста, имейте в виду, что дженерики для меня новы, хотя я давно использую универсальный List; P

ОБНОВЛЕНИЕ 2:

открытый частичный класс MainWindow: Window { открытый делегат IEnumerable SearchInputTextStrategy (строковый параметр);

    private SearchInputTextStrategy<ICustomer> _strategy;

    public MainWindow()
    {
        InitializeComponent();            

        IEnumerable<ICustomer> customers = DataService.GetCustomers();                  

        _strategy = new SearchInputTextStrategy<ICustomer>(SearchCustomers);           


        ElementUserControl.BindElements(customers, c => c.FirstName, c => c.SortId, ";", _strategy);

namespace ElementTextBoxV2
{      

        public partial class MainWindow : Window
        {
            public delegate IEnumerable<ICustomer> SearchInputTextStrategy<ICustomer>(string param);

            private SearchInputTextStrategy<ICustomer> _strategy;

            public MainWindow()
            {
                InitializeComponent();            

                IEnumerable<ICustomer> customers = DataService.GetCustomers();                  

                _strategy = new SearchInputTextStrategy<ICustomer>(SearchCustomers);           


                ElementUserControl.BindElements(customers, c => c.FirstName, c => c.SortId, ";", _strategy);

                IEnumerable<ICustomer> selectedElements =  ElementUserControl.SelectedElements<ICustomer>();
            }

            // Just a Test-Methode to assure the delegate works
            public IEnumerable<ICustomer> SearchCustomers(string param)
            {
                IEnumerable<ICustomer> foundCustomers = new List<ICustomer>();
                return foundCustomers;
            }         
        }
    }

Сценарий состоит в том, что пользователь поместил TextBoxUserControl в MainWindow, и он должен передать делегат, указывающий на searchMethod. Я реализовал это с помощью SearchCustomers_Method. Проблема в том, что C # не может решить, что:

    Error   1   The best overloaded method match for 'ElementTextBoxV2.ElementsView.BindElements<ElementTextBoxV2.ICustomer,string,int>(System.Collections.Generic.IEnumerable<ElementTextBoxV2.ICustomer>, System.Func<ElementTextBoxV2.ICustomer,string>, System.Func<ElementTextBoxV2.ICustomer,int>, string, ElementTextBoxV2.Provider.SearchInputTextStrategy<ElementTextBoxV2.ICustomer>)' has some invalid arguments

Error   2   Argument 5: cannot convert from 'ElementTextBoxV2.MainWindow.SearchInputTextStrategy<ElementTextBoxV2.ICustomer>' to 'ElementTextBoxV2.Provider.SearchInputTextStrategy<ElementTextBoxV2.ICustomer>'    

Вы видите проблему? В любом случае, пользователь должен передать делегата с тем же определением, которое имеет метод BindElements!

Ответы [ 2 ]

2 голосов
/ 28 ноября 2010
private SearchInputTextStrategy<T, string> _searchStrategy;

public void BindElements<T, TDisplayProperty,TSortProperty>
(
       IEnumerable<T> dataObjects,
       Func<T, TDisplayProperty> selectorDisplayMember,
       Func<T, TSortProperty> selectorSortMember,
       string delimiter,
       SearchInputTextStrategy<T, string> searchStrategy
)
{
    _searchStrategy = searchStrategy;
}
2 голосов
/ 28 ноября 2010

Странно, что ваш SearchInputTextStrategy имеет два параметра типа, но на самом деле использует только один ... но вам просто нужно указать аргументы типа в типе параметра. Например:

public void BindElements<T, TDisplayProperty,TSortProperty>
(
    IEnumerable<T> dataObjects,
    Func<T, TDisplayProperty> selectorDisplayMember,
    Func<T, TSortProperty> selectorSortMember,
    string delimiter,
    SearchInputTextStrategy<T, TDisplayProperty> searchStrategy
)

Я только догадался о том, какими должны быть аргументы типа - вы действительно не сказали, что хотите, чтобы параметр представлял.

Вы не сможете легко иметь поле правильного типа в вашем классе, потому что сам класс не знает используемых параметров типа. Вполне возможно, что вы действительно должны сделать свой класс универсальным или создать другой класс , который может надлежащим образом обрабатывать делегаты. Без дополнительной информации очень трудно понять, какая именно.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...