小编thi*_*hat的帖子

没有setter的C#属性 - 如何从构造函数中设置?

为什么你可以从构造函数设置一个get-only auto-property?下面的代码显示了如何从构造函数设置属性,但使用反射显示在幕后确实没有setter.如果在IL中甚至不存在setter方法,它是如何从构造函数调用中设置的?

void Main()
{
    var obj = new GetOnlyProperty("original value");
    Console.WriteLine(obj.Thing); //works, property gets set from ctor

    //get the set method with reflection, is it just hidden..?
    //nope, null reference exception
    typeof(GetOnlyProperty)
        .GetProperty("Thing", BindingFlags.Instance | BindingFlags.Public)
        .GetSetMethod()
        .Invoke(obj, new object[]{"can't set me to this, setter doen't exist!"});
}

public class GetOnlyProperty
{
    public string Thing { get; }

    public GetOnlyProperty(string thing)
    {
        Thing = thing;
    }
}
Run Code Online (Sandbox Code Playgroud)

c# cil

10
推荐指数
1
解决办法
2223
查看次数

我应该使用 Task.Run 在同步上下文中等待任务吗?

我有一个无法转换的 ASPX 页面,async但它async在同步上下文中使用了一些方法。它调用它们的方式是这样的:

public void MySyncMethod()
{
    var myTask = Task.Run(() => _myField.DoSomethingAsync());
    myTask.Wait();
    //use myTask.Result
}
Run Code Online (Sandbox Code Playgroud)

就async/await和/或阻塞而言,这样做与以下有什么区别吗?

public void MySyncMethod()
{
    var myTask = _myField.DoSomethingAsync(); //just get the Task direct, no Task.Run
    myTask.Wait();
    //use myTask.Result
}
Run Code Online (Sandbox Code Playgroud)

我假设以前的开发人员Task.Run出于某种原因添加了。但是HttpContext当工作在不同的线程上运行时,我遇到了访问事物的问题。

有理由在Task.Run这里使用吗?

c# asp.net async-await

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

从给定的类型创建 Expression<Func<T, object>>

我希望通过在代表给定类型的属性成员访问的代码中构建表达式来动态使用 CsvHelper。

我试图将这些表达式传递给的方法具有以下签名:

    public virtual CsvPropertyMap<TClass, TProperty> Map<TProperty>( Expression<Func<TClass, TProperty>> expression )
    {
        //
    }
Run Code Online (Sandbox Code Playgroud)

因此,对于要映射的任何给定类型,您通常会调用它,如下所示(对于具有名为“stringProperty”的属性的类型):

mapper.Map(x => x.StringProperty);
Run Code Online (Sandbox Code Playgroud)

传入一个 lambda 表达式,该 lambda 表达式在内部转换为 Expression<Func<T, object>>

我尝试使用表达式在代码中创建此表达式。在编译时它一切正常(因为它返回一个Expression<Func<TModel, object>>),但在运行时我得到一个异常“不是成员访问”。这是采用表示我要映射的属性的 PropertyInfo 对象的代码:

    private Expression<Func<TModel, object>> CreateGetterExpression( PropertyInfo propertyInfo )
    {
        var getter = propertyInfo.GetGetMethod();

        Expression<Func<TModel, object>> expression = m => getter.Invoke( m, new object[] { } );
        return expression;
    }
Run Code Online (Sandbox Code Playgroud)

基本上,如何在代码中正确构建该表达式?

c# reflection lambda expression

-1
推荐指数
1
解决办法
1341
查看次数

标签 统计

c# ×3

asp.net ×1

async-await ×1

cil ×1

expression ×1

lambda ×1

reflection ×1