저는 C# 코드 조각에 어려움을 겪었습니다. 문제의 해결책을 찾았지만 이상적인 것은 아닙니다 (아래 DoSomething_WorksButNotIdeal() 참조).C# 캐스팅 및 제네릭
내가 원하는 것은 if, else 문 (어떤 형식을 지원할 것인가에 따라 잠재적으로 방대함) 대신 일반적인 형식을 사용하는 것입니다. 그러나 작동시키지 못합니다. DoSomething_HelpMe() 메서드에서이를 증명하려고했습니다.
어쨌든 이것을 달성 할 수 있습니까? 어떤 도움이라도 대단히 감사합니다.
public interface ITag
{
string TagName { get; }
Type Type { get; }
object InMemValue { get; set; }
object OnDiscValue { get; set; }
}
을하고보다 구체적인하기 위해 ITag<T>
를 사용 : 당신이 가질 수 없습니다
public interface ITag
{
string TagName { get; }
Type Type { get; }
}
public interface ITag<T> : ITag
{
T InMemValue { get; set; }
T OnDiscValue { get; set; }
}
public class Tag<T> : ITag<T>
{
public Tag(string tagName)
{
TagName = tagName;
}
public string TagName { get; private set; }
public T InMemValue { get; set; }
public T OnDiscValue { get; set; }
public Type Type{ get{ return typeof(T);} }
}
public class MusicTrack
{
public MusicTrack()
{
TrackTitle = new Tag<string>("TrackTitle");
TrackNumber = new Tag<int>("TrackNumber");
Tags = new Dictionary<string, ITag>();
Tags.Add(TrackTitle.TagName, TrackTitle);
Tags.Add(TrackNumber.TagName, TrackNumber);
}
public IDictionary<string,ITag> Tags;
public ITag<string> TrackTitle { get; set; }
public ITag<int> TrackNumber { get; set; }
}
public static class Main
{
public static void DoSomething_WorksButNotIdeal()
{
MusicTrack track1 = new MusicTrack();
MusicTrack track2 = new MusicTrack();
// Set some values on the tracks
foreach (ITag tag in track1.Tags.Values)
{
Type type = tag.Type;
if (type == typeof(string))
{
((ITag<string>) tag).InMemValue = ((ITag<string>)track2.Tags[tag.TagName]).OnDiscValue;
}
else if (type == typeof(int))
{
((ITag<int>)tag).InMemValue = ((ITag<int>)track2.Tags[tag.TagName]).OnDiscValue;
}
else if (type == typeof(bool))
{
((ITag<bool>)tag).InMemValue = ((ITag<bool>)track2.Tags[tag.TagName]).OnDiscValue;
}
// etc etc
else
{
throw new Exception("Unsupported type.");
}
}
}
public static void DoSomething_HelpMe()
{
MusicTrack track1 = new MusicTrack();
MusicTrack track2 = new MusicTrack();
// Set some values on the tracks
foreach (ITag tag in track1.Tags.Values)
{
Type type = tag.Type;
// THIS OBVIOUSLY DOESN'T WORK BUT I'M JUST TRYING TO DEMONSTRATE WHAT
// I'D IDEALLY LIKE TO ACHIEVE
((ITag<typeof(type)>)tag).InMemValue = ((ITag<typeof(type)>)track2.Tags[tag.TagName]).OnDiscValue;
}
}
}
마크, 답장을 보내 주셔서 대단히 감사합니다. 두 가지 제안은 가능한 해결책입니다 :-) 문법적으로 나는 Copy 클래스의 메서드를 사용하여 클래스를 지우지 않기 때문에 1 번째 제안을 선호하지만 어떤 것이 더 잘 수행되는지 알고 싶습니다.하나의 다운 캐스트 만 있기 때문에 2 위를 추측합니다. 첫 번째 변수는 값 변수 인 경우 참조 변수와 더 나쁜 상자 및 unbox에 대해 다운 캐스트하고 업 캐스트해야합니다. –