我想知道在类之间传递上下文的最佳方式是什么。我应该使用 ref 参数还是简单地将上下文作为参数传递?最好是构造函数,但在静态方法的情况下,最好的方法是什么? IE。性能、安全、设计等。将上下文作为参数传递是否会影响性能?如果不同的线程在使用引用时同时处理上下文,是否可能会发生冲突?
主.cs
static void Main(string[] args)
{
var context = new MyEntities();
var myClass = new MyClass(context);
myClass.AddPerson();
// or
Person.AddPerson(ref context);
}
我的类.cs
public class MyClass
{
public void MyClass(MyEntities context) { }
public void AddPerson()
{
context.People.AddObject(new Person());
}
}
MySecondClass.cs
public partial class Person
{
public static AddPerson(ref MyEntities context)
{
// Do something
}
}
最佳答案
ref 关键字意味着您通过引用传递指针,因此更改变量的值将为调用者更改它。又名:
static void Main(string[] args)
{
var context = new MyEntities();
Person.AddPerson(ref context);
// context is now null
}
调用:
public partial class Person
{
public static AddPerson(ref MyEntities context)
{
context = null;
}
}
在这种情况下,您不会通过引用传递。请记住,变量是指向对象的指针,因此简单地传递它不会像在 C++ 中那样复制对象。
关于c# - 将实体上下文传递给其他方法和对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16154346/