|
分類:[C#]
属性(Attribute)あたりで出来そうな気がするのですが、調べ切れていないので教えてください。
よろしくお願いします。
--- 環境
VS 2022 Pro 17.13.6
C# 13(理由は後述)
Framework 4.7.2
対象プラットフォーム x86
COM 相互運用機能の登録はチェック済み
Excel(x86) Microsoft 365 Apps for enterprise
--- Book1.xlsm
Private Sub CommandButton1_Click()
Dim cls As Object
On Error GoTo Catch
Set cls = CreateObject("ClassLibrary1.Class1")
MsgBox cls.Count ' 2
MsgBox cls(0) ' AIUEO
MsgBox cls(1) ' 123
MsgBox cls.Item_2("name") ' AIUEO ' デフォルトインデクサ or 既定のプロパティ にしたい
Call cls.Add("hoge", "hoo")
MsgBox cls.Count ' 3
MsgBox cls(2) ' hoo
MsgBox cls.Item_2("hoge") ' hoo
cls(2) = "bar"
MsgBox cls(2) ' bar
MsgBox cls.Item_2("hoge") ' bar ' デフォルトインデクサ or 既定のプロパティ にしたい
GoTo Finally
Catch:
MsgBox "(" & Err.Number & ")" & Err.Description
Finally:
Set cls = Nothing
End Sub
--- Class1.cs
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace ClassLibrary1;
[ComVisible(true)]
[Guid("C6D56925-BF75-47C5-A0A2-2359FF021ADF")]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface IClass1
{
public object this[short idx] { get; set; }
public object this[string key] { get; set; }
public void Add(string key, object obj);
public short Count { get; }
}
[ComVisible(true)]
[Guid("BF5F036C-7602-4CEF-BE69-F1E22A463087")]
[ClassInterface(ClassInterfaceType.AutoDual)]
public class Class1:IClass1
{
private Dictionary<string, object> list = new Dictionary<string, object>();
public Class1()
{
// test data
list.Add("name", "AIUEO");
list.Add("num", (short)123);
}
public object this[short idx]
{
get { return list.Skip(idx).First().Value; }
set { list[list.Skip(idx).First().Key] = value; }
}
public object this[string key]
{
get { return list[key]; }
set { list[key] = value; }
}
public void Add(string key, object value) => list.Add(key, value);
public short Count => (short)list.Count;
}
---
属性 'ClassInterface' はこの宣言型では無効です。'アセンブリ, クラス' 宣言でのみ有効です。
C# 7.3 では、修飾子 'public' はこの項目に対して有効ではありません。'8.0' 以上の言語バージョンをご使用ください。
C# 7.3 では、修飾子 'public' はこの項目に対して有効ではありません。'8.0' 以上の言語バージョンをご使用ください。
⇒上記の点からC# 12に変更。変更箇所はClassLibrary1.csproj参照のこと
--- ClassLibrary1.csproj
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{77A4FFE1-6014-4FFD-B508-A7CD4991D732}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ClassLibrary1</RootNamespace>
<AssemblyName>ClassLibrary1</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<LangVersion>12</LangVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
</PropertyGroup>
|