[英]using c# generics extension methods to operate on a class and not a collection
I have the following types defined:
-----------------------------------
interface IMyInterface<T> where T : class
{
void BlahBlah();
}
abstract class MyBase<T> : IMyInterface<T> where T : class
{
public abstract T MyInfo { get; set; }
public abstract T MyInfo2 { get; set; }
public void BlahBlah()
{
Console.WriteLine(MyInfo + ", " + MyInfo2);
}
}
class MyConcreteClass1<T> : MyBase<T> where T : class
{
public override T MyInfo { get; set; }
public override T MyInfo2 { get; set; }
}
class MyConcreteClass2<T> : MyBase<T> where T : class
{
public override T MyInfo { get; set; }
public override T MyInfo2 { get; set; }
}
public static class DataOperations<T, U> where T : class where U : class
{
public static U Operate(this T source, U destination)
{
var sourceProps = source.GetType().GetProperties();
var destinationProps = destination.GetType().GetProperties();
.
.
.
return destination;
}
}
我想要做的是在实现中做的是对上述两个类进行操作,如下所示:
MyConcreteClass1<String> class1 = new MyConcreteClass1<String>();
class1.MyInfo = "Some Value";
class1.MyInfo2 = "another value";
MyConcreteClass2<String> class2 = new MyConcreteClass2<String>();
var c2 = class1.Operate(class2);
问题是我在 DataOperations 类名上得到:“CS1106 扩展方法必须在非通用静态类中定义”。
声明类型必须是非泛型的,但方法可以是泛型的。 考虑一下:
public static class DataOperations
{
public static U Operate<T, U>(this T source, U destination)
where T : class where U : class
{ // ...
}
}
将泛型定义移到方法上:
public static class DataOperations
{
public static U Operate<T, U>(this T source, U destination) where T : class where U : class
{
// Whatever
}
}
必须在非通用静态(顶级)类中定义扩展方法 - 作为错误状态。
因此,您需要将DataOperations
类DataOperations
非泛型,而将方法本身DataOperations
泛型:
public static class DataOperations
{
public static U Operate<T, U>(this T source, U destination) where T : class where U : class
{
var sourceProps = source.GetType().GetProperties();
var destinationProps = destination.GetType().GetProperties();
.
.
.
return destination;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.