我有 Person 下面的类,它有一个其依赖项的列表。我的问题是如何在屏幕上呈现它,假设我有一张人员表,当单击另一个受抚养人表时,如果有很多记录,可能会花费数据库大量时间。如何做到这一点才能获得更好的性能?在下面的示例中,每次获取 Person 属性的 Dependents 时,我都会通过函数搜索 Person id。
public class Dependent
{
public int Id { get; set; }
public string Name { get; set;}
}
public class Person
{
public int Id { get; set; }
public string Name { get; set;}
private List<Dependent> _dependents;
public List<Dependent> Dependentes
{
get {return _dependents = getDependentsForDatabase(this.Id);}
set { _dependents = value };
}
var dependents = new Person().Dependents;
Console.WriteLine(dependents);
我正在使用 Subsonic,但无论银行连接工具如何,我都想要一些想法。
1.为什么不继承List?
List<T> does implement several interfaces.
2.如何根据对象中的属性对列表进行排序
SortedList<T>.
3.为 C# 自动属性赋予初始值的最佳方法是什么?
Constructor, Field
4.如何根据DateTime类型的生日计算某人的年龄?
class Program
{
public int CalculateAge(DateTime birthDate)
{
DateTime currentDate = DateTime.Today;
int age = currentDate.Year - birthDate.Year;
if (birthDate.Date > currentDate.AddYears(-age))
age--;
return age;
}
static void Main(string[] args)
{
DateTime birthDate = new DateTime(1998, 8, 15); // My birth date
int age = new Program().CalculateAge(birthDate);
Console.WriteLine("Age: " + age);
}
}
5.如何使用实体框架检索插入实体的Id?
将 DbContext.Add() 方法与异步 SaveChanges 结合使用:如果您正在使用异步操作,则可以使用等待 DbContext.SaveChangesAsync(),然后访问生成的 Id。
using (var dbContext = new YourDbContext())
{
// Create a new entity
var newEntity = new YourEntity
{
// Populate properties
};
// If using asynchronous SaveChanges
dbContext.YourEntities.Add(newEntity);
await dbContext.SaveChangesAsync();
int newEntityId = newEntity.Id;
}
6.字段和属性有什么区别?
public class MyClass
{
private int myField;
// Property declaration
public int MyProperty
{
get { return myField; } // Getter
set { myField = value; } // Setter
}
}
7.如何查看实体框架生成的SQL?
几个选项取决于您使用的实体框架版本和您的开发环境。
8.如何设置HttpClient请求的Content-Type header?
// Set the Content-Type header
client.DefaultRequestHeaders.Accept.
Add(new MediaTypeWithQualityHeaderValue("application/json"));
9.如何使用类型变量调用泛型方法?
MethodInfo methodInfo = typeof(MyClass).GetMethod();
MethodInfo genericMethodInfo = methodInfo.MakeGenericMethod(typeArgument);