如何使托管包装类使用另一个托管包装类的属性?
我的想法是我想重用代码而不是重复它。下面,UnManagedB 派生自 UnmanagementA。这两个结构都有相应的托管包装器,如下所示。我想从 ManagedA 派生 ManagedB,以便我可以将 ManagedA 中的属性重用于 ManagedB。问题是两个类都有自己的指向非托管对象的指针。派生中的非托管对象就是我想要的,并且我希望所有属性都使用 UnManagedB 指针。有什么办法可以做到这一点吗?
struct UnManagedA {
unsigned int size;
};
struct UnManagedB:UnManagedA {
int length;
int width;
};
public ref class A : public System::IDisposable {
public:
A();
!A();
~A();
property System::UInt32 Size {
System::UInt32 get();
void set(System::UInt32 value);
}
internal:
UnmanagedA* GetUnmanaged() { return obj1; }
private:
UnmanagedA* obj1;
};
public ref class B : public System::IDisposable, public A {
public:
B();
!B();
~B();
property System::UInt32 Length {
System::UInt32 get();
void set(System::UInt32 value);
}
property System::UInt32 Width {
System::UInt32 get();
void set(System::UInt32 value);
}
internal:
UnmanagedB* GetUnmanaged() { return obj2; }
private:
UnmanagedB* obj2;
};
The idea is that I would like to reuse code and not duplicate it. Below, UnManagedB derives from UnmanagedA. Both the structs have their corresponding managed wrappers as shown below. I would like to derive the ManagedB from ManagedA so that I can reuse the properties in ManagedA for ManagedB. The issue is both the class have their own pointers to unmanaged objects. The unmanaged object in the derived is all I want and I want all the properties to use UnManagedB pointer. Is there any way to do this?
struct UnManagedA {
unsigned int size;
};
struct UnManagedB:UnManagedA {
int length;
int width;
};
public ref class A : public System::IDisposable {
public:
A();
!A();
~A();
property System::UInt32 Size {
System::UInt32 get();
void set(System::UInt32 value);
}
internal:
UnmanagedA* GetUnmanaged() { return obj1; }
private:
UnmanagedA* obj1;
};
public ref class B : public System::IDisposable, public A {
public:
B();
!B();
~B();
property System::UInt32 Length {
System::UInt32 get();
void set(System::UInt32 value);
}
property System::UInt32 Width {
System::UInt32 get();
void set(System::UInt32 value);
}
internal:
UnmanagedB* GetUnmanaged() { return obj2; }
private:
UnmanagedB* obj2;
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
虽然它们都有自己的指向非托管对象的指针,但想必这些指针都指向完全相同的未托管对象——所以应该没有问题。如果您不同意,请描述一个无法正常工作的具体使用场景,然后我们可以更好地提供帮助。
While they both have their own pointer to unmanaged objects, presumably those pointers point to the exact same unamanged object--so there should be no problem. If you disagree describe a specific usage scenario where it wouldn't work correctly, and then we can better help.