当前位置: 首页>>代码示例>>C#>>正文


C# Func.Invoke方法代码示例

本文整理汇总了C#中Func.Invoke方法的典型用法代码示例。如果您正苦于以下问题:C# Func.Invoke方法的具体用法?C# Func.Invoke怎么用?C# Func.Invoke使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Func的用法示例。


在下文中一共展示了Func.Invoke方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: CompareOne

        private void CompareOne(Func<IComparableObject, object> getElement, string pathToContainer, IComparableObject before, IComparableObject after, List<Difference> differences, List<AttributeChange> attributeChanges,
                                string name)
        {
            var valueBefore = getElement.Invoke(before);
            var valueAfter = getElement.Invoke(after);

            if (valueBefore is IEnumerable<IComparableObject>)
            {
                differences.AddRange(CheckArray(getElement, pathToContainer, before, after));
                return;
            }

            if (valueBefore is IComparableObject)
            {
                differences.AddRange(Compare(AddToPath(pathToContainer, before.IdentifyingText), valueBefore as IComparableObject, valueAfter as IComparableObject));
                return;
            }

            foreach (var comparer in AttributeComparers.Union(new[] { new DefaultAttributeComparer() }))
                if (comparer.CanHandle(valueBefore))
                {
                    var result = comparer.Compare(name, valueBefore, valueAfter);
                    if (result != null)
                        attributeChanges.Add(result);
                    return;
                }

            throw new Exception("Not handled: " + valueBefore.GetType());
        }
开发者ID:kennethchoe,项目名称:ObjectDiff,代码行数:29,代码来源:ObjectComparer.cs

示例2: RegiterWithAction

        private ActionResult RegiterWithAction(RegisterUserModel model, Func<ActionResult> successAction, Func<ActionResult> defaultAction)
        {
            if (!_auth.ValidateCaptcha()) {
                ModelState.AddModelError("", "Sorry, we failed to validate your captcha. Please try again.");                
                defaultAction.Invoke();
            }

            if (ModelState.IsValid)
            {
                var email = model.Email;
                var password = model.Password;

                if (_auth.RegisterNewUser(email, password))
                {
                    _notification.NotifyUserOnRegistration(email, password);
                    return successAction.Invoke();
                }
                else
                {
                    ModelState.AddModelError("", "Sorry, user with such email already exist. Please register with different email.");
                }
            }

            return defaultAction.Invoke();
        }
开发者ID:TGebreyes,项目名称:trackyt.net,代码行数:25,代码来源:RegistrationController.cs

示例3: GetMetadataForProperty

        public override ModelMetadata GetMetadataForProperty(Func<object> modelAccessor, Type containerType, string propertyName)
        {
            var propertyDescriptor = this.GetTypeDescriptor(containerType).GetProperties().Find(propertyName, true);

            //DateTime: For DateTime model accessors, perform the conversion to the users time zone
            if (propertyDescriptor.PropertyType == typeof(DateTime))
            {
                var value = DateTime.MinValue;
                var rawValue = modelAccessor.Invoke();
                if (rawValue != null)
                {
                    value = TimeZoneManager.GetUserTime((DateTime) rawValue);
                }

                return this.GetMetadataForProperty(() => value, containerType, propertyDescriptor);
            }

            //DateTime?: For DateTime? model accessors, perform the conversion to the users time zone
            if (propertyDescriptor.PropertyType == typeof(DateTime?))
            {
                return this.GetMetadataForProperty(() =>
                                                   {
                                                       var dt = (DateTime?) modelAccessor.Invoke();
                                                       return !dt.HasValue ? dt : TimeZoneManager.GetUserTime(dt.Value);
                                                   }, containerType, propertyDescriptor);
            }

            //Everything else
            return this.GetMetadataForProperty(modelAccessor, containerType, propertyDescriptor);
        }
开发者ID:cthibault,项目名称:dailyscores,代码行数:30,代码来源:DateTimeMetadataProvider.cs

示例4: GetMetadataForProperty

        public override ModelMetadata GetMetadataForProperty(Func<object> modelAccessor, Type containerType, string propertyName)
        {
            //Null checks
            if (containerType == null) throw new ArgumentNullException("containerType");
            if (string.IsNullOrEmpty(propertyName)) throw new ArgumentNullException("propertyName");
            var propertyDescriptor = this.GetTypeDescriptor(containerType).GetProperties().Find(propertyName, true);
            if (propertyDescriptor == null) throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, "Property not found (container='{0}', property='{1}'.", containerType.FullName, propertyName));

            //DateTime: For DateTime model accessors, perform the conversion to the users time zone
            if (propertyDescriptor.PropertyType == typeof(DateTime))
            {
                var value = DateTime.MinValue;
                var rawValue = modelAccessor.Invoke();
                if (rawValue != null)
                    value = TimeZoneManager.GetUserTime((DateTime)rawValue);

                return GetMetadataForProperty(() => value, containerType, propertyDescriptor);
            }

            //DateTime?: For DateTime? model accessors, perform the conversion to the users time zone
            if (propertyDescriptor.PropertyType == typeof(DateTime?))
                return GetMetadataForProperty(() =>
                {
                    var dt = (DateTime?)modelAccessor.Invoke();
                    return !dt.HasValue ? dt : TimeZoneManager.GetUserTime(dt.Value);
                }, containerType, propertyDescriptor);

            //Everything else
            return GetMetadataForProperty(modelAccessor, containerType, propertyDescriptor);
        }
开发者ID:jonezy,项目名称:Epilogger,代码行数:30,代码来源:DateTimeMedataDataProvider.cs

示例5: Invoke

        public Task Invoke(IOwinContext context, Func<Task> next)
        {
            var request = context.Request;

            if (request.Method != "GET")
                return next.Invoke();

            if (_draftRuleNamesPath.IsWildcardMatch(request.Path))
                return GetDraftRuleNames(context);

            if (!_versionRuleNamesPath.IsWildcardMatch(request.Path))
                return next.Invoke();

            var pathSegmnts = request.Path.Value
                .Split('/')
                .Where(p => !string.IsNullOrWhiteSpace(p))
                .Select(HttpUtility.UrlDecode)
                .ToArray();

            if (pathSegmnts.Length < 2)
                throw new HttpException((int)HttpStatusCode.BadRequest, "Path has too few segments. Expecting " + _versionRuleNamesPath.Value);

            var versionText = pathSegmnts[1];
            int version;
            if (!int.TryParse(versionText, out version))
                throw new HttpException((int)HttpStatusCode.BadRequest, "The version must be a whole number " + _versionRuleNamesPath.Value);

            if (request.Method == "GET")
                return GetRuleNames(context, version);

            return next.Invoke();
        }
开发者ID:Bikeman868,项目名称:Urchin,代码行数:32,代码来源:RuleNamesEndpoint.cs

示例6: SetUpUnits

 public void SetUpUnits(Func<IUnitBuilder> builder)
 {
     Archers(builder.Invoke());
     Chariots(builder.Invoke());
     Legions(builder.Invoke());
     Settlers(builder.Invoke());
 }
开发者ID:SPDiswal,项目名称:ExtenCiv,代码行数:7,代码来源:FourUnitsWithActions.cs

示例7: CheckArray

        private IEnumerable<Difference> CheckArray(Func<IComparableObject, object> getElement, string pathToContainer, IComparableObject before, IComparableObject after)
        {
            var valueBefore = (IEnumerable<IComparableObject>) getElement.Invoke(before);
            var arrayBefore = valueBefore.ToList();

            var valueAfter = getElement.Invoke(after) as IEnumerable<IComparableObject>;
            if (valueAfter == null)
                throw new ArgumentException("after object signature does not match with before object: missing " + valueBefore);

            var arrayAfter = valueAfter.ToList();

            var deletedElements = arrayBefore.Where(x => !arrayAfter.Exists(y => x.Id == y.Id));
            var addedElements = arrayAfter.Where(x => !arrayBefore.Exists(y => x.Id == y.Id));

            var differences = new List<Difference>();
            differences.AddRange(deletedElements.Select(x => new DeletedObject(pathToContainer, before, x)));
            differences.AddRange(addedElements.Select(x => new AddedObject(pathToContainer, after, x)));

            foreach (var elementBefore in arrayBefore)
            {
                var elementAfter = arrayAfter.FirstOrDefault(x => x.Id == elementBefore.Id);
                if (elementAfter != null)
                    differences.AddRange(Compare(AddToPath(pathToContainer, before.IdentifyingText), elementBefore, elementAfter));
            }

            return differences;
        }
开发者ID:kennethchoe,项目名称:ObjectDiff,代码行数:27,代码来源:ObjectComparer.cs

示例8: Envelope

 public Envelope(Func<double, double> function, double time, double start, double end, int size)
 {
     double[] timePoints = new double[size + 1];
     double[] valuPoints = new double[size + 1];
     decimal delta = (decimal)(time / size);
     decimal start_ = (decimal)start;
     decimal end_ = (decimal)end;
     decimal inc = (end_ - start_) / size;
     decimal x;
     int indexcounter = 0;
     if (start_ < end_)
     {
         for (x = start_; x <= end_; x += inc)
         {
             timePoints[indexcounter] = (double)(indexcounter * delta);
             valuPoints[indexcounter] = function.Invoke((double)x);
             indexcounter++;
         }
     }
     else
     {
         for (x = start_; x >= end_; x += inc)
         {
             timePoints[indexcounter] = (double)(indexcounter * delta);
             valuPoints[indexcounter] = function.Invoke((double)x);
             indexcounter++;
         }
     }
     double maxvalue = 0;
     double minvalue = 0;
     //Move function up if parts are negative until its all in the positive.
     for (int x2 = 0; x2 < size + 1; x2++)
     {
         if (valuPoints[x2] < minvalue)
             minvalue = valuPoints[x2];
     }
     //Get the biggest element.
     for (int x2 = 0; x2 < size + 1; x2++)
     {
         valuPoints[x2] = valuPoints[x2] + (minvalue * -1);
         if (valuPoints[x2] > maxvalue)
             maxvalue = valuPoints[x2];
     }
     //Now scale the values to the time.
     if (maxvalue != 0)
     {
         for (int x2 = 0; x2 < size + 1; x2++)
         {
             valuPoints[x2] = Math.Abs((valuPoints[x2] / maxvalue) * time);
         }
     }
     this.timePoints = timePoints;
     clampArray(valuPoints);
     this.valuPoints = valuPoints;
     arraylength = timePoints.Length;
     sort();
     recalculateMaxTime();
 }
开发者ID:YJh2046,项目名称:BlockFun,代码行数:58,代码来源:Envelope.cs

示例9: Run

        public static void Run(string title, bool isBaseline, int tryCount, Func<object> action)
        {
            Console.Write("  {0,-20} ", title + ":");
            object result = null;
            Stopwatch bestTimer = null;

            for (int i = 0; i < tryCount; i++) {
                for (int j = 0; j < 5; j++) {
                    Thread.Sleep(10);
                    GC.WaitForPendingFinalizers();
                    GC.GetTotalMemory(true);
                }
                var timer = new Stopwatch();
                timer.Start();
                result = action.Invoke();
                timer.Stop();
                if (bestTimer==null || bestTimer.Elapsed > timer.Elapsed)
                    bestTimer = timer;
            }

            double time = bestTimer.Elapsed.TotalMilliseconds;
            if (time < 0.05) {
                // Too short, let's use average instead of min time
                for (int j = 0; j < 5; j++) {
                    Thread.Sleep(10);
                    GC.WaitForPendingFinalizers();
                    GC.GetTotalMemory(true);
                }
                var timer = new Stopwatch();
                timer.Start();
                int tryCount2 = tryCount*10;
                for (int i = tryCount2; i > 0; i--)
                    result = action.Invoke();
                timer.Stop();
                time = timer.Elapsed.TotalMilliseconds / tryCount2;
            }

            bool timeInMS = time >= 0.1;
            Console.Write("{0,9:F3}{1}", timeInMS ? time : time * 1000, timeInMS ? "ms" : "ns");

            if (isBaseline) {
                Baseline = time;
                Console.Write(", baseline");
            }
            else
                Console.Write(", x{0,5:F2}", time / Baseline);

            if (DisplayEnumeratorType) {
                if (result is IEnumerable<int> && !(result is List<int>))
                    Console.Write(" ({0})", (result as IEnumerable<int>).GetEnumerator().GetType().Name);
                else if (result is IEnumerable<string>)
                    Console.Write(" ({0})", (result as IEnumerable<string>).GetEnumerator().GetType().Name);
            }
            Console.WriteLine();
        }
开发者ID:alexyakunin,项目名称:linq-vs-raw-code,代码行数:55,代码来源:Measurement.cs

示例10: NameValueCell

        public NameValueCell(string name, Func<string> valueGet, Action<string> valueSet)
        {
            this.BackgroundColor = UIColor.Clear;
            this.Frame = new RectangleF (0, 0, 100, 100);

            int labelXPos = 10;
            int label2XPos = 75;
            NameLabel = new UILabel (new RectangleF (
                labelXPos, 11,  label2XPos-(labelXPos+5), 21));
            NameLabel.AutoresizingMask = UIViewAutoresizing.None;
            NameLabel.BackgroundColor = UIColor.Clear;
            NameLabel.Font = UIFont.SystemFontOfSize (14);
            NameLabel.AdjustsFontSizeToFitWidth = true;
            NameLabel.TextAlignment = UITextAlignment.Right;
            NameLabel.Text = name;
            NameLabel.TextColor = UIColor.Blue;
            this.Add (NameLabel);

            ValueLabel = new UILabel (new RectangleF (
                label2XPos, 11,  this.Frame.Width-(label2XPos+10), 21));
            ValueLabel.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
            ValueLabel.BackgroundColor = UIColor.Clear;
            ValueLabel.Font = UIFont.BoldSystemFontOfSize (17);
            ValueLabel.AdjustsFontSizeToFitWidth = true;
            ValueLabel.Text = valueGet.Invoke ();
            this.Add (ValueLabel);

            ValueTextField = new UITextField (new RectangleF (
                label2XPos, 11,  this.Frame.Width-(label2XPos+10), 21));

            ValueTextField.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
            ValueTextField.BackgroundColor = UIColor.Clear;
            ValueTextField.Font = UIFont.BoldSystemFontOfSize (17);
            ValueTextField.AdjustsFontSizeToFitWidth = true;
            ValueTextField.Text = valueGet.Invoke ();
            ValueTextField.ReturnKeyType = UIReturnKeyType.Done;
            ValueTextField.ClearButtonMode = UITextFieldViewMode.Always;
            ValueTextField.ShouldReturn = delegate {
                ValueTextField.ResignFirstResponder ();
                return true;
            };

            ValueTextField.EditingDidEnd += delegate {
                _valueSet.Invoke (ValueTextField.Text);
            };

            this.Add (ValueTextField);

            _valueGet = valueGet;
            _valueSet = valueSet;
        }
开发者ID:bholmes,项目名称:XamarinEvolve2013Project,代码行数:51,代码来源:NameValueCell.cs

示例11: WithoutConfiguration

        public static void WithoutConfiguration(
            Func<string, int> fakedDelegate)
        {
            "establish"
                .x(() => fakedDelegate = A.Fake<Func<string, int>>());

            "when faking a delegate type and invoking without configuration"
                .x(() => fakedDelegate.Invoke("foo"));

            "it should be possible to assert the call"
                .x(() => A.CallTo(() => fakedDelegate.Invoke("foo")).MustHaveHappened());

            "it should be possible to assert the call without specifying invoke method"
                .x(() => A.CallTo(() => fakedDelegate("foo")).MustHaveHappened());
        }
开发者ID:huoxudong125,项目名称:FakeItEasy,代码行数:15,代码来源:FakingDelegates.cs

示例12: Run

 /// <summary>
 /// Runs a string command and returns the result parsed by a provided parser
 /// </summary>
 /// <param name="command">Command to send to ECU</param>
 /// <param name="parser">Anonymous method to parse ECU response</param>
 /// <returns>ECU response parsed by provided parser</returns>
 public Task<object> Run(string command, Func<string, object> parser)
 {
     return Task.Run(async () =>
     {
         return parser.Invoke(await Run(command));
     });
 }
开发者ID:Milstein,项目名称:strados,代码行数:13,代码来源:Elm327VehicleService.cs

示例13: runBuild

        private BuildRunResults runBuild(string buildExecutable, string arguments, string target, Func<bool> abortIfTrue)
        {
            if (_configuration.MSBuildAdditionalParameters.Length > 0)
                arguments += " " + _configuration.MSBuildAdditionalParameters;
            var timer = Stopwatch.StartNew();
            DebugLog.Debug.WriteInfo("Running build: {0} {1}", buildExecutable, arguments);
            Process process = new Process();
            process.StartInfo = new ProcessStartInfo(buildExecutable, arguments);
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.CreateNoWindow = true;

            process.Start();
            string line;
            var buildResults = new BuildRunResults(target);
            var lines = new List<string>();
            while ((line = process.StandardOutput.ReadLine()) != null)
            {
                if (abortIfTrue.Invoke())
                {
                    process.Kill();
                    process.WaitForExit();
                    AutoTest.Core.DebugLog.Debug.WriteDebug("Aborting build run");
                    return new BuildRunResults(target);
                }
                lines.Add(line);
            }
            process.WaitForExit();
            timer.Stop();
            var parser = new MSBuildOutputParser(buildResults, lines.ToArray());
            parser.Parse();
            buildResults.SetTimeSpent(timer.Elapsed);
            return buildResults;
        }
开发者ID:dlsteuer,项目名称:AutoTest.Net,代码行数:35,代码来源:MSBuildRunner.cs

示例14: GetOrCreate

        public override object GetOrCreate(string key, Func<object> callback)
        {
            Mandate.ParameterNotNull(Instances, "[ThreadStatic]_reference");
            Mandate.ParameterNotNull(callback, "callback");

            return Instances.GetOrAdd(key, x => callback.Invoke());
        }
开发者ID:RebelCMS,项目名称:rebelcmsxu5,代码行数:7,代码来源:ThreadStaticScopedCache.cs

示例15: MinimizeGameOnce

        public Task MinimizeGameOnce(CancellationToken token, Func<GameInfo> getCurrentGame)
        {
            return Task.Factory.StartNew(() =>
                {
                    var currentGame = getCurrentGame.Invoke();
                    while (!token.IsCancellationRequested)
                    {
                        var process = Process.GetProcessesByName(currentGame.ProcessName).FirstOrDefault();

                        if (process != null)
                        {
                                var gameWnd = PInvoke.FindWindow(currentGame.WindowTitle);
                                var wndState = PInvoke.GetWindowState(gameWnd);

                            if (gameWnd.ToInt32() != 0 && (wndState == 1 || wndState == 3))
                            {
                                PInvoke.MinimizeWindow(currentGame.WindowTitle);
                                break;
                            }
                        }

                        Thread.Sleep(1000); // Sleep for a second
                    }
                });
        }
开发者ID:ra4king,项目名称:PureSeeder3,代码行数:25,代码来源:GameMinimizer.cs


注:本文中的Func.Invoke方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。