ProxyAttribute Класс
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Указывает, что для типа объекта требуется настраиваемый прокси-сервер.
public ref class ProxyAttribute : Attribute, System::Runtime::Remoting::Contexts::IContextAttribute
[System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=false, Inherited=true)]
public class ProxyAttribute : Attribute, System.Runtime.Remoting.Contexts.IContextAttribute
[System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=false, Inherited=true)]
[System.Runtime.InteropServices.ComVisible(true)]
public class ProxyAttribute : Attribute, System.Runtime.Remoting.Contexts.IContextAttribute
[System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=false, Inherited=true)]
[System.Runtime.InteropServices.ComVisible(true)]
[System.Security.SecurityCritical]
public class ProxyAttribute : Attribute, System.Runtime.Remoting.Contexts.IContextAttribute
[<System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=false, Inherited=true)>]
type ProxyAttribute = class
inherit Attribute
interface IContextAttribute
[<System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=false, Inherited=true)>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type ProxyAttribute = class
inherit Attribute
interface IContextAttribute
[<System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=false, Inherited=true)>]
[<System.Runtime.InteropServices.ComVisible(true)>]
[<System.Security.SecurityCritical>]
type ProxyAttribute = class
inherit Attribute
interface IContextAttribute
Public Class ProxyAttribute
Inherits Attribute
Implements IContextAttribute
- Наследование
- Атрибуты
- Реализации
Примеры
[AttributeUsageAttribute(AttributeTargets::Class)]
[System::Security::Permissions::SecurityPermissionAttribute
(System::Security::Permissions::SecurityAction::LinkDemand,
Flags=System::Security::Permissions::SecurityPermissionFlag::Infrastructure)]
[System::Security::Permissions::SecurityPermissionAttribute
(System::Security::Permissions::SecurityAction::InheritanceDemand,
Flags=System::Security::Permissions::SecurityPermissionFlag::Infrastructure)]
public ref class MyProxyAttribute: public ProxyAttribute
{
public:
MyProxyAttribute(){}
// Create an instance of ServicedComponentProxy
virtual MarshalByRefObject^ CreateInstance( Type^ serverType ) override
{
return ProxyAttribute::CreateInstance( serverType );
}
virtual RealProxy^ CreateProxy( ObjRef^ objRef1, Type^ serverType, Object^ serverObject, Context^ serverContext ) override
{
MyProxy^ myCustomProxy = gcnew MyProxy( serverType );
if ( serverContext != nullptr )
{
RealProxy::SetStubData( myCustomProxy, serverContext );
}
if ( ( !serverType->IsMarshalByRef) && (serverContext == nullptr) )
{
throw gcnew RemotingException( "Bad Type for CreateProxy" );
}
return myCustomProxy;
}
};
[MyProxyAttribute]
ref class CustomServer: public ContextBoundObject
{
public:
CustomServer()
{
Console::WriteLine( "CustomServer Base Class constructor called" );
}
void HelloMethod( String^ str )
{
Console::WriteLine( "HelloMethod of Server is invoked with message : {0}", str );
}
};
[AttributeUsage(AttributeTargets.Class)]
public class MyProxyAttribute : ProxyAttribute
{
public MyProxyAttribute()
{
}
// Create an instance of ServicedComponentProxy
public override MarshalByRefObject CreateInstance(Type serverType)
{
return base.CreateInstance(serverType);
}
public override RealProxy CreateProxy(ObjRef objRef1,
Type serverType,
object serverObject,
Context serverContext)
{
MyProxy myCustomProxy = new MyProxy(serverType);
if(serverContext != null)
{
RealProxy.SetStubData(myCustomProxy,serverContext);
}
if((!serverType.IsMarshalByRef)&&(serverContext == null))
{
throw new RemotingException("Bad Type for CreateProxy");
}
return myCustomProxy;
}
}
[MyProxyAttribute]
public class CustomServer :ContextBoundObject
{
public CustomServer()
{
Console.WriteLine("CustomServer Base Class constructor called");
}
public void HelloMethod(string str)
{
Console.WriteLine("HelloMethod of Server is invoked with message : " + str);
}
}
<SecurityPermissionAttribute(SecurityAction.Demand, Flags := SecurityPermissionFlag.Infrastructure), _
AttributeUsage(AttributeTargets.Class)> _
Public Class MyProxyAttribute
Inherits ProxyAttribute
Public Sub New()
End Sub
' Create an instance of ServicedComponentProxy
Public Overrides Function CreateInstance(serverType As Type) As MarshalByRefObject
Return MyBase.CreateInstance(serverType)
End Function 'CreateInstance
Public Overrides Function CreateProxy(objRef1 As ObjRef, serverType As Type, _
serverObject As Object, serverContext As Context) As RealProxy
Dim myCustomProxy As New MyProxy(serverType)
If Not (serverContext Is Nothing) Then
RealProxy.SetStubData(myCustomProxy, serverContext)
End If
If Not serverType.IsMarshalByRef And serverContext Is Nothing Then
Throw New RemotingException("Bad Type for CreateProxy")
End If
Return myCustomProxy
End Function 'CreateProxy
End Class
<MyProxyAttribute()> _
Public Class CustomServer
Inherits ContextBoundObject
Public Sub New()
Console.WriteLine("CustomServer Base Class constructor called")
End Sub
Public Sub HelloMethod(str As String)
Console.WriteLine("HelloMethod of Server is invoked with message : " + str)
End Sub
End Class
Комментарии
Примените текущий атрибут к типам, которым требуются пользовательские прокси-серверы. Класс ProxyAttribute можно использовать для перехвата инструкции new (New в Visual Basic) путем извлечения из ProxyAttribute и размещения атрибута на дочернем объекте ContextBoundObject. (Размещение атрибута прокси-сервера на дочернем MarshalByRefObject элементе не поддерживается.)
Замечание
Этот класс делает спрос на связь и спрос на наследование на уровне класса. Возникает SecurityException , если непосредственный вызывающий или производный класс не имеют разрешения инфраструктуры. Дополнительные сведения о требованиях к безопасности см. в разделе "Требования ссылки".
Конструкторы
| Имя | Описание |
|---|---|
| ProxyAttribute() |
Инициализирует новый экземпляр ProxyAttribute класса со значениями по умолчанию. |
Свойства
| Имя | Описание |
|---|---|
| TypeId |
При реализации в производном классе получает уникальный идентификатор для этого Attribute. (Унаследовано от Attribute) |
Методы
| Имя | Описание |
|---|---|
| CreateInstance(Type) |
Создает неинициализированный MarshalByRefObject или прозрачный прокси-сервер в зависимости от того, может ли указанный тип существовать в текущем контексте. |
| CreateProxy(ObjRef, Type, Object, Context) |
Создает экземпляр прокси-сервера удаленного взаимодействия для удаленного объекта, описанного указанным ObjRefи расположенным на сервере. |
| Equals(Object) |
Возвращает значение, указывающее, равен ли этот экземпляр указанному объекту. (Унаследовано от Attribute) |
| GetHashCode() |
Возвращает хэш-код для этого экземпляра. (Унаследовано от Attribute) |
| GetPropertiesForNewContext(IConstructionCallMessage) |
Возвращает свойства для нового контекста. |
| GetType() |
Возвращает Type текущего экземпляра. (Унаследовано от Object) |
| IsContextOK(Context, IConstructionCallMessage) |
Проверяет указанный контекст. |
| IsDefaultAttribute() |
При переопределении в производном классе указывает, является ли значение этого экземпляра значением по умолчанию для производного класса. (Унаследовано от Attribute) |
| Match(Object) |
При переопределении в производном классе возвращает значение, указывающее, равен ли этот экземпляр указанному объекту. (Унаследовано от Attribute) |
| MemberwiseClone() |
Создает неглубокую копию текущей Object. (Унаследовано от Object) |
| ToString() |
Возвращает строку, представляющую текущий объект. (Унаследовано от Object) |
Явные реализации интерфейса
| Имя | Описание |
|---|---|
| _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) |
Сопоставляет набор имен соответствующему набору идентификаторов диспетчеризации. (Унаследовано от Attribute) |
| _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) |
Извлекает сведения о типе объекта, который можно использовать для получения сведений о типе для интерфейса. (Унаследовано от Attribute) |
| _Attribute.GetTypeInfoCount(UInt32) |
Возвращает количество предоставляемых объектом интерфейсов для доступа к сведениям о типе (0 или 1). (Унаследовано от Attribute) |
| _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
Предоставляет доступ к свойствам и методам, предоставляемым объектом. (Унаследовано от Attribute) |