English 中文(简体)
指明T应属于其他类型类别的通用类别
原标题:Specify generics class where T should be subclass of other type
  • 时间:2011-10-18 16:25:18
  •  标签:
  • c#
  • generics

我在这里试图做的是,即便是可能的话,也不肯定。

页: 1 BaseViewModel<T>,我希望接受从继承的类型。 实体

考虑这一法典:

public abstract class BaseViewModel<T> : NotificationObject, INavigationAware
{

public T MyEntity;

public SomeMethod()
{
MyEntity.SomeEntityProperty = SomeValue;
}

}

因此,我要说,我从<代码>Entity继承的,因此,I KNOW表示,它将有某种意向。

Is this possible?

最佳回答

救世的回答完全正确,我只是想描述这个概念。

你们需要的是“基因类型的限制”;具体地说,作为T的类型必须符合某些行为(例如从物体或比物体更衍生的界面衍生出来的),从而增加允许你在不进一步投放的情况下与该物体做些什么(一般在一般情况下可以避免)。

As Salvatore s answer shows, GTCs are defined using the "where" keyword:

public abstract class BaseViewModel<T> :
    NotificationObject,
    INavigationAware

    where T : Entity;
{
   ...

地球资源中心基本称,任何T必须(无论远处)从实体获得。 这使你能够将T视作一个实体(除新Ts的即时情况外;这要求增加一个TC,而不论实际通用参数类型如何来自实体。 你可以指实体上出现的任何方法,获取/确定任何领域或财产。

您还可以指出:

  • The type must be a class (where T:class), or alternately must be a ValueType (where T:struct). This either permits or prevents comparison and assignment of a T instance to null, which also allows or prevents use of the null-coalescing operator ??.
  • The type must have a parameterless constructor (where T:new()). This allows instantiations of Ts using the new keyword, by ensuring at compile-time that all types used as Ts have a constructor that takes no parameters.
问题回答
public abstract class BaseViewModel<T> :
    NotificationObject,
    INavigationAware

    where T : Entity
{

    public T MyEntity;

    public SomeMethod()
    {
        MyEntity.SomeEntityProperty = SomeValue;
    }

}

Just use the where 关键词:

public abstract class BaseViewModel<T> : NotificationObject, INavigationAware
    where T:Entity
{
...




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签