本文整理汇总了C#中Func.?.Invoke方法的典型用法代码示例。如果您正苦于以下问题:C# Func.?.Invoke方法的具体用法?C# Func.?.Invoke怎么用?C# Func.?.Invoke使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Func
的用法示例。
在下文中一共展示了Func.?.Invoke方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: DisposableBoolean
public DisposableBoolean(Func<bool> getter, bool initialValue = true)
: this(new Func<bool, bool>(b => {
getter?.Invoke();
return b;
}), initialValue)
{
}
示例2: CreatePipeline
private IRequestPipeline CreatePipeline(
Func<IEnumerable<Uri>, IConnectionPool> setupPool, Func<ConnectionSettings, ConnectionSettings> settingsSelector = null, IDateTimeProvider dateTimeProvider = null)
{
var pool = setupPool(new[] { TestClient.CreateNode(), TestClient.CreateNode(9201) });
var settings = new ConnectionSettings(pool, TestClient.CreateConnection());
settings = settingsSelector?.Invoke(settings) ?? settings;
return new FixedPipelineFactory(settings, dateTimeProvider ?? DateTimeProvider.Default).Pipeline;
}
示例3: Convert
internal Exception Convert(Func<RealmExceptionCodes, Exception> overrider = null)
{
var message = (messageLength != IntPtr.Zero) ?
new string(messageBytes, 0 /* start offset */, (int)messageLength, Encoding.UTF8)
: "No further information available";
NativeCommon.delete_pointer(messageBytes);
return overrider?.Invoke(type) ?? RealmException.Create(type, message);
}
示例4: ProfileWorkerAsync
private static async Task ProfileWorkerAsync( Func<int,int, IUserProfileServices,CancellationToken, ILogger, Task> action, int serverTimeOutms, int clientTimeOutms, ManualResetEvent workerDone, CancellationToken ct, ILogger logger) {
while (!ct.IsCancellationRequested) {
try {
await action?.Invoke(ServiceReadAfterConnectTimeoutMs, ClientResponseReadTimeoutMs, null, ct, logger);
} catch (Exception ex) when (!ex.IsCriticalException()) {
logger?.LogError(Resources.Error_UserProfileServiceError, ex.Message);
}
}
workerDone.Set();
}
示例5: HumanLikeWalking
public async Task<PlayerUpdateResponse> HumanLikeWalking(GeoCoordinate targetLocation,
double walkingSpeedInKilometersPerHour, Func<bool> functionExecutedWhileWalking)
{
var speedInMetersPerSecond = walkingSpeedInKilometersPerHour / 3.6;
var sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude);
var distanceToTarget = LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation);
// Logger.Write($"Distance to target location: {distanceToTarget:0.##} meters. Will take {distanceToTarget/speedInMetersPerSecond:0.##} seconds!", LogLevel.Info);
var nextWaypointBearing = LocationUtils.DegreeBearing(sourceLocation, targetLocation);
var nextWaypointDistance = speedInMetersPerSecond;
var waypoint = LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing);
//Initial walking
var requestSendDateTime = DateTime.Now;
var result =
await
_client.Player.UpdatePlayerLocation(waypoint.Latitude, waypoint.Longitude,
_client.Settings.DefaultAltitude);
do
{
var millisecondsUntilGetUpdatePlayerLocationResponse =
(DateTime.Now - requestSendDateTime).TotalMilliseconds;
sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude);
var currentDistanceToTarget = LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation);
if (currentDistanceToTarget < 40)
{
if (speedInMetersPerSecond > SpeedDownTo)
{
//Logger.Write("We are within 40 meters of the target. Speeding down to 10 km/h to not pass the target.", LogLevel.Info);
speedInMetersPerSecond = SpeedDownTo;
}
}
nextWaypointDistance = Math.Min(currentDistanceToTarget,
millisecondsUntilGetUpdatePlayerLocationResponse / 1000 * speedInMetersPerSecond);
nextWaypointBearing = LocationUtils.DegreeBearing(sourceLocation, targetLocation);
waypoint = LocationUtils.CreateWaypoint(sourceLocation, nextWaypointDistance, nextWaypointBearing);
requestSendDateTime = DateTime.Now;
result =
await
_client.Player.UpdatePlayerLocation(waypoint.Latitude, waypoint.Longitude,
_client.Settings.DefaultAltitude);
functionExecutedWhileWalking?.Invoke(); // look for pokemon
await Task.Delay(Math.Min((int)(distanceToTarget / speedInMetersPerSecond * 1000), 3000));
} while (LocationUtils.CalculateDistanceInMeters(sourceLocation, targetLocation) >= 30);
return result;
}
示例6: Log
public bool Log(LogLevel logLevel, Func<string> messageFunc, Exception exception, params object[] formatParameters)
{
string message = messageFunc?.Invoke();
if (message != null)
{
_logLevel = logLevel;
_message = messageFunc() ?? _message;
_exception = exception;
}
return true;
}
示例7: AesCtrCryptoTransform
/// <summary>
/// ctor
/// </summary>
/// <param name="key"></param>
/// <param name="counterBufferSegment"></param>
/// <param name="aesFactory"></param>
/// <exception cref="ArgumentException">
/// <paramref name="counterBufferSegment"/> needs to have the same length as <see cref="AesConstants.STR_AES_BLOCK_SIZE"/>.
/// </exception>
public AesCtrCryptoTransform(byte[] key, ArraySegment<byte> counterBufferSegment, Func<Aes> aesFactory = null)
{
if (counterBufferSegment.Count != AesConstants.AES_BLOCK_SIZE)
throw new ArgumentException($"{nameof(counterBufferSegment)}.Count must be {AesConstants.STR_AES_BLOCK_SIZE}.", nameof(counterBufferSegment));
_aes = aesFactory?.Invoke() ?? CipherFactory.Aes();
_aes.Mode = CipherMode.ECB;
_aes.Padding = PaddingMode.None;
Buffer.BlockCopy(counterBufferSegment.Array, counterBufferSegment.Offset, _counterBuffer.Value, 0, AesConstants.AES_BLOCK_SIZE);
_cryptoTransform = _aes.CreateEncryptor(rgbKey: key, rgbIV: null);
}
示例8: WhereHasClass
public static IEnumerable<IElement> WhereHasClass(
this IElement rootElement,
IList<string> classes,
Func<IElement, bool> filter = default(Func<IElement, bool>))
{
return (from e in rootElement.Descendents<IElement>()
where e.HasAttribute("class")
where filter?.Invoke(e) ?? true
let names = e.GetAttribute("class").Split(' ')
from name in classes
where names.Any(p => p.Equals(name, StringComparison.OrdinalIgnoreCase))
orderby classes.IndexOf(name)
select e).Distinct().ToList();
}
示例9: TryFocusImpl
static async Task<bool> TryFocusImpl(FrameworkElement element, Func<FrameworkElement, bool> focusAction)
{
if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
{
return false;
}
var loadedElement = await WaitForElementLoaded(element);
if (focusAction?.Invoke(element) ?? false)
return true;
// TODO: MoveFocus almost always requires its descendant elements to be fully loaded, we
// have no way of knowing if they are so we should try again before bailing out.
return false;
}
示例10: CompileEachFileAsync
// Helper that delegates execution
private static async Task CompileEachFileAsync(string path, string searchPattern, string SaveFolder, SearchOption searchOption, Func<string, string, Task> doAsync)
{
// Avoid blocking the caller for the initial enumerate call.
await Task.Yield();
var sw = Stopwatch.StartNew();
// really need a simple exception swallowing file system walker, enumerations suck with exceptions !
foreach (string file in Directory.EnumerateFiles(path, searchPattern, searchOption))
{
await doAsync?.Invoke(file, SaveFolder);
}
if(Verbose > 0)
System.Console.WriteLine($"processing time: {sw.Elapsed}");
}
示例11: FirstWhereHasClass
public static IElement FirstWhereHasClass(
this IElement rootElement,
IList<string> classes,
Func<IElement, bool> filter = default(Func<IElement, bool>))
{
return (from e in rootElement.Descendents<IElement>()
where e.HasAttribute("class")
where filter?.Invoke(e) ?? true
let names = e.GetAttribute("class").Split(' ')
let a = (from cl in classes
from name in names
where cl.Equals(name, StringComparison.OrdinalIgnoreCase)
select cl).FirstOrDefault()
where a != null
let index = classes.IndexOf(a)
orderby index
select e).FirstOrDefault();
}
示例12: CreateVariable
BoundVariable CreateVariable(VariableName name, VariableKind kind, Func<BoundExpression> initializer)
{
switch (kind)
{
case VariableKind.LocalVariable:
Debug.Assert(initializer == null);
return new BoundLocal(new SourceLocalSymbol(_routine, name.Value, kind));
case VariableKind.StaticVariable:
return new BoundStaticLocal(new SourceLocalSymbol(_routine, name.Value, kind), initializer?.Invoke());
case VariableKind.GlobalVariable:
Debug.Assert(initializer == null);
return new BoundGlobalVariable(name);
default:
Debug.Assert(initializer == null);
throw Roslyn.Utilities.ExceptionUtilities.UnexpectedValue(kind);
}
}
示例13: PrintCommandConsoleFriendly
private static void PrintCommandConsoleFriendly(TextWriter console, string commandName, string oneLineDescription, int offset, Func<int, string> getFormatString = null)
{
var intendation = offset + 3;
var minWordLength = 6;
var commandFormatString = getFormatString?.Invoke(offset) ?? " {0,-" + offset + "}- {1}";
var prefix = new String(' ', intendation);
var commandStrings = ConsoleUtil.SplitStringHumanReadable(string.Format(commandFormatString, commandName,
oneLineDescription), ConsoleUtil.ConsoleWidth, splitpattern: null);
console.WriteLine(commandStrings.First());
foreach (var commandString in commandStrings.Skip(1)) {
if (ConsoleUtil.ConsoleWidth - intendation > minWordLength)
{
var secondLineCommandStrings = ConsoleUtil.SplitStringHumanReadable(commandString, ConsoleUtil.ConsoleWidth - intendation, splitpattern: null);
secondLineCommandStrings.ForEach(it => console.WriteLine(prefix + it));
}
else
{
console.WriteLine(prefix + commandString);
}
}
}
示例14: GetIndexSettingsAsync
/// <inheritdoc/>
public Task<IGetIndexSettingsResponse> GetIndexSettingsAsync(Func<GetIndexSettingsDescriptor, IGetIndexSettingsRequest> selector, CancellationToken cancellationToken = default(CancellationToken)) =>
this.GetIndexSettingsAsync(selector?.Invoke(new GetIndexSettingsDescriptor()), cancellationToken);
示例15: SimulatePipeline
public ISimulatePipelineResponse SimulatePipeline(Func<SimulatePipelineDescriptor, ISimulatePipelineRequest> selector) =>
this.SimulatePipeline(selector?.Invoke(new SimulatePipelineDescriptor()));