简体   繁体   English

将实体上下文传递给其他方法和对象

[英]Passing Entity Context to other methods and objects

I was wondering what is the best way to pass the context between classes. 我想知道在类之间传递上下文的最佳方法是什么。 Should I be using the ref parameter or simply pass the context as a parameter? 我应该使用ref参数还是简单地将上下文作为参数传递? Preferably to constructor but in the case of a static method what is the best approach? 最好是构造函数,但在静态方法的情况下,最好的方法是什么? Ie performance, safety, design, etc. Is there a performance hit in passing the context as a parameter? 即性能,安全性,设计等。将上下文作为参数传递是否会影响性能? Could possibly conflicts happen if different threads are working on the context at the same time when using references? 如果不同的线程在使用引用的同时处理上下文,可能会发生冲突吗?

Main.cs Main.cs

static void Main(string[] args)
{
    var context = new MyEntities();

    var myClass = new MyClass(context);
    myClass.AddPerson();
    // or
    Person.AddPerson(ref context);
}

MyClass.cs MyClass.cs

public class MyClass
{
    public void MyClass(MyEntities context) { }

    public void AddPerson()
    {
        context.People.AddObject(new Person());
    }
}

MySecondClass.cs MySecondClass.cs

public partial class Person
{
    public static AddPerson(ref MyEntities context)
    {
        // Do something
    }
}

the ref keyword means that you are passing the pointer by reference, so changing the value of the variable will change it for the caller. ref关键字表示您通过引用传递指针,因此更改变量的值将为调用者更改它。 AKA: 又名:

static void Main(string[] args)
{
    var context = new MyEntities();
    Person.AddPerson(ref context);

    // context is now null
}

calling: 电话:

public partial class Person
{
    public static AddPerson(ref MyEntities context)
    {
        context = null;
    }
}

In this case, you would not was to pass by reference. 在这种情况下,你不会通过引用传递。 Remember that the variable is a pointer to the object, so simply passing it will not make a copy of the object like it would in C++. 请记住,变量是指向对象的指针,因此简单地传递它不会像在C ++中那样复制对象。

Using ref is totally unnecessary here. 在这里使用ref是完全没必要的。 When passing around objects you're actually passing a copy of the reference (which is itself a value type that points to an object in the heap). 在传递对象时,您实际上传递了引用的副本(它本身是指向堆中对象的值类型)。 Using the ref keyword, you're passing the "reference value" by reference (confused yet?). 使用ref关键字,您通过引用传递“参考值”(混淆了吗?)。 This means that the reference could actually be changed outside the scope of the function, which doesn't seem practical in really any circumstance and is just an opportunity for weird bugs. 这意味着实际上可以在函数范围之外更改引用,这在任何情况下都不实用,并且只是奇怪错误的机会。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM