C#线程中的只读字段是否安全?
public class Foo
{
private readonly int _someField;
public Foo()
{
_someField = 0;
}
public Foo(int someField)
{
_someField = someField;
}
public void SomeMethod()
{
doSomething(_someField);
}
}
Run Code Online (Sandbox Code Playgroud)
经历了一些帖子:
- 在C#中将字段标记为只读有什么好处?- JaredPar认为,曾经构建的只读字段是不可变的,因此是安全的.
- Readonly Fields和Thread Safety,表明如果构造函数做了很多工作,那么存在一些风险.
因此,如果在上面的代码中使用readonly字段,并且构造函数很轻,那么它是否是线程安全的?如果someField是ref类型(例如字符串数组)怎么办?
最近我看到一个人大量使用var和default关键字来声明变量(以及每个声明),如下所示:
var employee = default(Employee); //Employee is a class
var errorInfo = default(ErrorInfo); //ErrorInfo is struct; Blank is default value
var salary = default(Double);
var isManager = default(Boolean?);
Run Code Online (Sandbox Code Playgroud)
而不是使用:
Employee employee = null; //Employee is a class
ErrorInfo errorInfo = Blank; //ErrorInfo is struct; Blank is default value
Double salary = 0.0;
Boolean? isManager = null;
Run Code Online (Sandbox Code Playgroud)
或者,而不是使用偶数:
Employee employee; //Employee is a class
ErrorInfo errorInfo; //ErrorInfo is struct; Blank is default value
Double salary;
Boolean? isManager;
Run Code Online (Sandbox Code Playgroud)
现在使用var和default来声明每个变量 …
我们如何绑定到当前datacontext的父/兄弟(即表示当前datacontext的source属性)?
我不是在谈论绑定到父控件的属性(该情况涉及目标的父而不是源的父) - 并且可以通过使用RelativeSourceMode = FindAncestor轻松完成.
RelativeSourceMode = PreviousData提供对数据项的先前兄弟的绑定的有限支持,但不提供对父节点或其他兄弟节点的绑定.
虚拟示例:(
假设INPC就位)
如何将ComboBox的ItemsSource绑定到ViewModel的Departments属性?
public class Person
{
public string Name { get; set; }
public string Department { get; set; }
}
public class PersonViewModel
{
public List<Person> Persons { get; set; }
public List<string> Departments { get; set; }
public PersonViewModel()
{
Departments = new List<string>();
Departments.Add("Finance");
Departments.Add("HR");
Departments.Add("Marketing");
Departments.Add("Operations");
Persons = new List<Person>();
Persons.Add(new Person() { Name = "First", Department = "HR" });
Persons.Add(new Person() { Name = "Second", …
Run Code Online (Sandbox Code Playgroud)