标签: func

Cunc中的C#歧义+扩展方法+ lambdas

我一直试图通过这篇文章:

http://blogs.msdn.com/wesdyer/archive/2008/01/11/the-marvels-of-monads.aspx

......第1页上的内容让我感到不舒服.特别是,我试图围绕Compose <>()函数,我为自己写了一个例子.考虑以下两个Func:

Func<double, double> addTenth = x => x + 0.10;
Func<double, string> toPercentString = x => (x * 100.0).ToString() + "%";
Run Code Online (Sandbox Code Playgroud)

没问题!很容易理解这两者的作用.

现在,按照本文中的示例,您可以编写一个通用的扩展方法来组合这些函数,如下所示:

public static class ExtensionMethods
{
 public static Func<TInput, TLastOutput> Compose<TInput, TFirstOutput, TLastOutput>(
  this Func<TFirstOutput, TLastOutput> toPercentString,
  Func<TInput, TFirstOutput> addTenth)
 {
  return input => toPercentString(addTenth(input));
 }
}
Run Code Online (Sandbox Code Playgroud)

精细.所以现在你可以说:

string x = toPercentString.Compose<double, double, string>(addTenth)(0.4);
Run Code Online (Sandbox Code Playgroud)

你得到字符串"50%"

到现在为止还挺好.

但这里有一些含糊不清的东西.假设您编写另一种扩展方法,现在您有两个函数:

public static class ExtensionMethods
{
 public static Func<TInput, TLastOutput> Compose<TInput, TFirstOutput, TLastOutput>(
  this Func<TFirstOutput, TLastOutput> toPercentString,
  Func<TInput, TFirstOutput> …
Run Code Online (Sandbox Code Playgroud)

c# generics monads extension-methods func

2
推荐指数
1
解决办法
1615
查看次数

System.Action <T>作为EventHandler

相信使用委托System.Action或System.Func作为EventDelegates而不是经典的EventHandler模​​式.因此我会遇到问题吗?

private bool disposed;

public event Action<IUnitOfWork, IContext> Disposing;

public void Dispose()
{
    if (this.disposed)
    {
        return;
    }

    if (null != this.Disposing)
    {
        this.Disposing(this, this.AttachedContext);
    }

    this.disposed = true;
}
Run Code Online (Sandbox Code Playgroud)

-

用法:

unitOfWorkInstance.Disposing += (u, c) => c.Rollback(u); // in my opinion more readable than
unitOfWorkInstance.Disposing += (sender, args) => args.AttachedContext.Rollback(sender as IUnitOfWork);
Run Code Online (Sandbox Code Playgroud)

抱歉可怕的englisch

.net c# action func event-handling

2
推荐指数
1
解决办法
5863
查看次数

具有多个参数的Func表达式

我正在尝试编写一个表达式,该表达式调用一个接受多个参数作为输入的方法,并且该表达式充当nhibernate查询引擎的where子句.目前我收到一条错误消息:

System.Exception:无法识别的方法调用: System.Func`3[[MyClass, Assembly, Version=9.123.434, Culture=neutral, PublicKeyToken=null],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=wjerkwr234],[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=234234123]]:Boolean Invoke(MyClass, Int32)

 Expression<Func<MyClass, int, bool>> restricton=
         (myClassObject, myNumber) => myClassObject.Property1== myNumber;

session
    .QueryOver<MyClass>()
    .Where(x =>x.Property2==1)
    .And(x=>restriction.Compile().Invoke(x, 2))
Run Code Online (Sandbox Code Playgroud)

我为什么要用表情?那么这是生成查询语句的函数的参数,并且条件可以改变

知道上面的代码有什么问题吗?

c# nhibernate delegates expression func

2
推荐指数
1
解决办法
3411
查看次数

Func <>有2个输出值

是否有可能创建一个具有2个输出值的函数?

我需要一种从对象中获取2个属性的方法,最好是通过表达式,因为易于使用.使用它和查询提供程序来选择多个字段.

protected Expression<Func<T, TProperty1, TProperty2>> Select2Properties { get; set; }

public MyClass(Expression<Func<T, TProperty1, TProperty2>> selector) {
   Select2Properties = selector;
}

// desired usage (pseudo)
x => (x.Property1, x.Property);
Run Code Online (Sandbox Code Playgroud)

我知道这是完全垃圾,但任何其他解决方案(例如需要2个表达式属性选择器或需要元组)会导致有时不可读的构造函数调用,尤其是当我需要2个以上的属性时:

x => x.Property1, x => x.Property2, x => x.Property3, x => x.Property4
// or 
x => Tuple.Create(x.Property1, x.Property2, x.Property3, x.Property4)
Run Code Online (Sandbox Code Playgroud)

有没有办法实现我想要的?

c# lambda expression func

2
推荐指数
1
解决办法
134
查看次数

无法从使用中推断出Func <T> Inkover错误.尝试显式指定类型参数

我一直在努力解决委托问题.我发送一个方法作为参数,它不获取参数并返回泛型类型Result<T>.

public Result<Content> GetContents()        
    {         
        var contents = new Result<List<TypeLibrary.Content>>();
        contents.Object = context.GetContents();
        if (contents.Object != null)
        {
                contents.Success = true;
            }
            else
            {
                contents.Success = false;
            }            
            return contents;
    }

public static Result<T> Invoker<T>(Func<Result<T>> genericFunctionName) where T : new()
    {
        Result<T> result;
        try
        {
            //do staff               
            result = genericFunctionName();                           
        }
        catch (Exception)
        {
            throw;
        }
        return result;
    }
Run Code Online (Sandbox Code Playgroud)

模特是

public class Result<T> where T : new()
{
    public bool Success { get; set; }
    public string Message …
Run Code Online (Sandbox Code Playgroud)

.net c# asp.net-mvc delegates func

2
推荐指数
1
解决办法
1051
查看次数

我什么时候应该使用C#Generic Func <T,Tresult>?

我一直在看C#的通用函数委托(Func)功能.

例:

// Instantiate delegate to reference UppercaseString method
Func<string, string> convertMethod = UppercaseString;
string name = "Dakota";

// Use delegate instance to call UppercaseString method
Console.WriteLine(convertMethod(name));
Run Code Online (Sandbox Code Playgroud)

我正在努力想到一个真实的生活场景,它们可能在我自己的应用程序中很有用.所以我想我会把问题提到那里.\

我非常感谢你的想法.

c# generics func

2
推荐指数
1
解决办法
1886
查看次数

如何等待Func <Task <string >>?

我想声明一个匿名方法来获取新的主题ID.一切都很好,除了await这个重新运行的匿名方法.

我的测试代码:

public async Task<int> AddNewTopic()
{
    using (var db = new MyDatabase()) //EF
    {
        Func<Task<string>> id = async () =>
        {
            var random = new Random();
            var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
                   .ToCharArray();
            string _id = string.Empty;

            for (byte i = 0; i < 32; i++)
            {
              _id += chars[random.Next(0, chars.Length)].ToString();
            }

            bool isExist = await db.Topics.SingleOrDefaultAsync(m => m.Id == _id) != null;

            //if this id already exists, try again...
            return !isExist ? _id : await id(); //error: Use …
Run Code Online (Sandbox Code Playgroud)

.net c# recursion func async-await

2
推荐指数
1
解决办法
1126
查看次数

如何在Swift中使用两个闭包作为参数创建函数?

我需要将这样的func从Objective-C转换为Swift语言。但是找不到示例,也无法获取如何在Swift中将2个闭包发送到func中。

例如,Objective-C中的原始功能:

- (void)getForDemoDataWithToken:(Token *)token
onSuccess:(void(^)(NSArray *demoData))success
onFailure:(void(^)(NSError *error))failure {
}
Run Code Online (Sandbox Code Playgroud)

我知道发送1个闭包作为参数:

getForDemoDataWithToken(token){(成功:字符串)->无效

//这里有一些代码

打印(成功)

}

但是,如何发送两个闭包?

谢谢

closures func swift

2
推荐指数
1
解决办法
1454
查看次数

将 Func 动态转换为对应的 Action

我正在尝试对函数和动作使用 Convert 方法,因此我可以避免编写接受 Func 类型委托的重复方法。Convert 方法来自Convert Action<T> 到 Action<object>

public class Program
{
    static void Main(string[] args)
    {
        var program = new Program();
        var mi = program.GetType().GetMethod("Function", BindingFlags.Instance | BindingFlags.Public);
        // Can be any version of Func
        var funcType = typeof(Func<int, int>);
        // Create action delegate somehow instead
        var del = mi.CreateDelegate(funcType, null);
        // Or dynamically convert the Func to a corresponding Action type (in this case Action<int>)
    }

    // Or find a way to pass it in as …
Run Code Online (Sandbox Code Playgroud)

c# delegates action func

2
推荐指数
1
解决办法
3321
查看次数

func foo(arr [] int)int和func foo(arr [num] int)int之间有什么区别

func foo(arr []int) int和之间有什么区别func foo(arr [*num*]int) int

这是两个例子:

func foo1(arr [2]int) int {
    arr[0] = 1
    return 0
}

func foo2(arr []int) int {
    arr[0] = 1
    return 0
}

func main() {
    var arr1 = [2]int{3, 4}
    var arr2 = []int{3, 4}
    foo1(arr1)
    println(arr1[0])      // result is 3, so arr in foo1(arr) is a copy
    foo2(arr2)
    println(arr2[0])      // result is 1, so arr in foo2(arr) is not a copy, it is a reference
}
Run Code Online (Sandbox Code Playgroud)

我还发现,如果我使用foo1(arr2) …

arrays func go slice

2
推荐指数
1
解决办法
117
查看次数