Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何创建泛型方法_C#_.net_Generics_Polymorphism_Casting - Fatal编程技术网

C# 如何创建泛型方法

C# 如何创建泛型方法,c#,.net,generics,polymorphism,casting,C#,.net,Generics,Polymorphism,Casting,我想创建一个方法,该方法将一些基类型作为参数,比较并检查它是否为派生类型,并基于此返回派生类型。 例如: Class A : IBase Class B : IBase 我的方法: Public IBase GetData(IBase type) { If type is A then { //do smthing return A } If type is B { //do smthing return B } } 请帮助….我想,从技术上讲

我想创建一个方法,该方法将一些基类型作为参数,比较并检查它是否为派生类型,并基于此返回派生类型。 例如:

Class A : IBase
Class B : IBase
我的方法:

Public IBase GetData(IBase type)
{
 If type is A then 
  {
   //do smthing
   return A
  }
 If type is B
  {
   //do smthing
   return B
  }
} 

请帮助….

我想,从技术上讲,正确使用多态性应该完全不需要进行类型检查

但是,要声明类型参数必须实现接口的泛型函数,如下所示:

public TBase GetData<TBase>(TBase type) where TBase : IBase
但正如我一开始提到的,也许将您的特例内容移动到IBase接口本身更合适。

这:

public T GetData<T>(T type) where T : IBase
{
   ....
}
public T GetData(T类型),其中T:IBase
{
....
}

您应该在代码标记为
//的地方采取您想要执行的步骤,做一些事情
并将其封装到类的方法中,我们称之为
DoSomething()
。您需要向
IBase
接口添加一个公共方法,名为
DoSomething()
。然后,type
A
和type
B
都将实现这个接口,并为这个“做点什么”方法提供不同的实现

那么,你的方法就是:

public IBase GetData(IBase type)
{
    type.DoSomething();
    return type; //not sure what this is for, maybe you're actually wanting to return type.GetType() ??
} 

有关如何使用多态性来消除对这些类型的if语句的需要的更多详细信息,请参阅本文。

这里的泛型有点过分了。让我们试试反思:

IBase type = GetSomeObjectOfDescendantType();
IBase newType = (IBase)Activator.CreateInstance(type.GetType());
您可以将其包装在一个方法中

public class MyDuplicator
{
    public static object GetNotClone(object X)
    {
        return Activator.CreateInstance(X.GetType());
    }
}
更多关于CreateInstance的信息


当然,只有当您的问题是关于在将类型A的对象放入时返回类型A的新对象时,这才适用。作为
.Clone()
的东西,但它是新构造的。

您能澄清一下,您想返回实际类型、该类型的新对象还是其他什么吗?我对这一点的最初反应(与Reddog的答案不谋而合)是,这听起来像是多态性的工作。如果我是你,我会重新评估我的设计,因为这有一股糟糕的代码味道。注意:
Activator.CreateInstance
非常慢,带有
new()
约束的泛型将更具性能,同时也更优雅(并获得编译时检查的好处)。@Lucero:我完全同意,我的目标是更具可读性的方法。反射也存在安全问题。
public class MyDuplicator
{
    public static object GetNotClone(object X)
    {
        return Activator.CreateInstance(X.GetType());
    }
}