我正在尝试使用C#和.NET 4.0创建通用列表
List<var> varlist = new List<var>();
此代码产生错误"上下文关键字'var'可能只出现在局部变量声明中"
原因是因为我想做这样的事情:
List<var> varList = new List<var>(); // Declare the generic list
List<Object1> listObj1; // List of Object1
List<Object2> listObj2; // List of Object2
varList = listObj1; // Assign the var list to list of Object1
varList = listObj2; // Re-assign the var list to the list of Object2
Run Code Online (Sandbox Code Playgroud)
有没有办法在C#.NET 4.0中执行此操作?
我正在尝试访问与传递给泛型的相同类型的属性.
看看代码:
class CustomClass
{
CustomProperty property {get; set;}
}
class CustomProperty
{
}
Main
{
// Create a new instance of my custom class
CustomClass myClass = new CustomClass();
// Create a new instance of another class that is the same type as myClass.property
CustomProperty myProp = new CustomProperty();
// Call the generic method
DynamicallyAccessPropertyOnObject<CustomProperty>(myProp, myClass);
}
private void DynamicallyAccessPropertyOnObject<T>(this T propertyToAccess, CustomClass class)
{
// I want to access the property (In class) that is the same type …Run Code Online (Sandbox Code Playgroud)